Home > front end >  File.readlines() doesn't work after running line a second time. Python
File.readlines() doesn't work after running line a second time. Python

Time:05-05

For a project, I've been storing data in a text document and I've noticed a problem when trying to receive that data back within the script. More specifically I'm using the readlines() method to get the data. When I use it the first time, it works just fine; however, any time after that it returns an empty list despite nothing in the document changing.

I've replicated the problem with this small chunk of code:

testDocRead = open("C:\\Users\\emowe\\OneDrive\\Desktop\\Python\\testDocument.txt", "r")
print(testDocRead.readlines()) #  attempt 1
print(testDocRead.readlines()) #  attempt 2

On the first attempt, everything works as intended. It prints:

['Filler\n', 'text\n', 'to\n', 'add\n', 'lines']

The second attempt simply prints:

[]

My questions are:

  • Why is this happening?
  • How do I update the value without nothing being returned?

CodePudding user response:

An explanation is that when you open the file for reading, and you use the first testDocRead.readlines(), it reads all the lines; thus putting the file pointer to the end of the file.

Any subsequent readlines() would just give nothing as it's at the end of the file.

You need to reset the file pointer back to the beginning.

i.e.

testDocRead = open("C:\\Users\\emowe\\OneDrive\\Desktop\\Python\\testDocument.txt", "r")
print(testDocRead.readlines()) #  attempt 1
testDocRead.seek(0)
print(testDocRead.readlines()) #  attempt 2

seek(0) resets the file pointer back to the beginning of the file.

Another option you can also use is close the file and open it again.

CodePudding user response:

It's because the readlines() function returns all the lines of the file , in the form of a list .

If you still want to print the output twice , write :

with open(path_name , 'r') as writer :
    data = reader.readlines() 

    print(f"{data}\n{data}") 

Or , if you want to print each line one by one , use .readline instead of .readlines .

At last , you can also use .seek method to restart your readlines function , by setting it to 0 .

  • Related