简体   繁体   中英

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()

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)

What you are after is file.seek() :

Example: ( based on your code )

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.seek(0)  # reset file pointer

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

lv_file.close()

This will reset the file pointer back to it's starting position.

pydoc file.seek :

seek(offset, whence=SEEK_SET) Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. Values for whence are:

SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive SEEK_CUR or 1 – current stream position; offset may be negative SEEK_END or 2 – end of the stream; offset is usually negative Return the new absolute position.

New in version 2.7: The SEEK_* constants

Update: A better way of counting the no. of lines in a file iteratively and only caring about the 2nd line:

def nth_line_and_count(filename, n):
    """Return the nth line in a file (zero index) and the no. of lines"""

    count = 0

    with open(filename, "r") as f:
        for i, line in enumerate(f):
            count += 1
            if i == n:
                value = line

    return count, value

nlines, line = nth_line_and_count("filename.txt", 1)

Since xreadlines() keeps a pointer to the last line it sent you, when you do

la_lines = la_file.readlines()

it basically remembers the index of the last line it gave you. when you close the file and then open it, it create a new iterator, and it again points to line 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM