Search code examples
pythoninputreadlines

Python Consecutive Reads From File


I have a Python script that is reading from a file. The first command counts the lines. The second one prints the second line although the second one is not working.

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
    lv_cnt = lv_cnt + 1

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

When I write it like this it works but I don't see why I would have to close the file and reopen it to get it to work. Is there some kind of functionality that I am misusing?

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
    lv_cnt = lv_cnt + 1

lv_file.close()

lv_file = open("filename.txt", "rw+")

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

Solution

  • A file object is an iterator. Once you've gone through all the lines, the iterator is exhausted, and further reads will do nothing.

    To avoid closing and reopening the file, you can use seek to rewind to the start:

    lv_file.seek(0)