I have some text files contain 7 lines when I try to print line 3 and 4 using the following code, it prints line 3 then it gives me an index out of range error
for root, subFolders, files in os.walk(folder):
for file in files:
if file.endswith('Init.txt'):
with open(os.path.join(root, file), 'r') as fRead:
line_3 = fRead.readlines()[3]
line_4 = fRead.readlines()[4]
print line_3
print line_4
However when I run either one of the following codes I get no errors
Code 1: Line 3 prints correctly
for root, subFolders, files in os.walk(folder):
for file in files:
if file.endswith('Init.txt'):
with open(os.path.join(root, file), 'r') as fRead:
line_3 = fRead.readlines()[3]
print line_3
Code 2: Line 4 prints correctly
for root, subFolders, files in os.walk(folder):
for file in files:
if file.endswith('Init.txt'):
with open(os.path.join(root, file), 'r') as fRead:
line_4 = fRead.readlines()[4]
print line_4
It seems as if I can't read both lines at the same time. This is so frustrating!
As stated in the documentation:
Help on built-in function readlines:
readlines(hint=-1, /) method of _io.TextIOWrapper instance Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Once you have consumed all lines, the next call to readlines
will be empty.
Change your function to store the result in a temporary variable:
with open(os.path.join(root, file)) as fRead:
lines = fRead.readlines()
line_3 = lines[3]
line_4 = lines[4]
print line_3
print line_4
The method readlines()
reads all lines in a file until it hits the EOF (end of file). The "cursor" is then at the end of the file and a subsequent call to readlines()
will not yield anything, because EOF is directly found.
Hence, after line_3 = fRead.readlines()[3]
you have consumed the whole file but only stored the fourth (!) line of the file (if you start to count the lines at 1).
If you do
all_lines = fRead.readlines()
line_3 = all_lines[3]
line_4 = all_lines[4]
you have read the file only once and saved every information you needed.
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.