user3896917
user3896917

Reputation:

Python's readline() function seeming not to work?

for some reason the readline() function in my following code seems to print nothing.

fileName = input()
    fileName += ".txt"
    fileA = open(fileName, 'a+')
    print("Opened", fileA.name)

    line = fileA.readline()
    print(line)
    fileA.close()

I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:

Opened file!!

I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.

Upvotes: 2

Views: 618

Answers (1)

user2555451
user2555451

Reputation:

Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.

If you want to read from the top, you need to place fileA.seek(0) just before you call readline:

fileA.seek(0)
line = fileA.readline()

Doing so sets the pointer to the top of the file.


Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.

Upvotes: 5

Related Questions