Having trouble with readline() function Python

user3896917

In my program, I open a file whose name the user enters in, planning to read and append the file (a+). I use seek(0) to move the pointer to the beginning of the file because it starts out at the end of the file when using a+. I then use the readline() function, and check if what the program read from the line was in a tuple. Here is the code:

fileName = input()
fileName += ".txt"
file = open(fileName, "a+")
fileName += ","
print("Opened", fileName, "reading:")
print()

#Reading operation selection
file.seek(0)
operation = file.readline() #Line 0 = operation
if operation not in ('+', '-', '*', '/'):
    print("Did not find valid operation in file.")
    print("Use a file with valid calculation code:")
    continue

I have a text file 'file.txt' containing exactly the following:

+
12
12
c

When I run the program and enter 'file', it returns 'Opened file.txt, reading: Did not find valid operation in file. Use a file with valid calculation code:'. So, I troubleshooted and ran the following code in a separate file:

fileName = input()
fileName += ".txt"
file = open(fileName, "a+")
fileName += ","
print("Opened", fileName, "reading:")
print()

#Reading operation selection
file.seek(0)
operation = file.readline() #Line 0 = operation

print(operation)

if operation not in ('+', '-', '*', '/'):
    print("Did not find valid operation in file.")
    print("Use a file with valid calculation code:")
    continue

I ran this program, entered 'file' as the file name, and it returns: Opened file.txt, reading:

+

Did not find valid operation in file.
Use a file with valid calculation code:

Why does the variable operation contain the single character that is the first line of file.txt and then a blank line after it?

Any help is appreciated, thanks!

robert

That's because Pythons readline also returns the newline at the end of the line. E.g. readline() -> "+\n".

You can use rstrip("\n") to remove the newline from your lines. E.g. readline().rstrip("\n").

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related