简体   繁体   English

无法使用readlines()索引超出范围错误同时读取两行

[英]Can't read two lines at the same time using readlines() index out of range error

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 当我尝试使用以下代码打印第3行和第4行时,我有一些文本文件包含7行,它打印了第3行,然后给了我索引超出范围的错误

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 代码1:第3行正确打印

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 代码2:第4行正确打印

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. _io.TextIOWrapper实例的readlines(hint = -1,/)方法返回流中的行列表。

 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. 消耗完所有行后,下一次对readlines调用将为空。

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). 方法readlines()读取文件中的所有行,直到命中EOF(文件结尾)为止。 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. 然后,“光标”位于文件的末尾,随后对readlines()调用将不会产生任何结果,因为直接找到了EOF。

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). 因此,在line_3 = fRead.readlines()[3]您已经使用了整个文件,但是只存储了文件的第四行(!)(如果您开始将行数为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. 您只读取了一次文件,并保存了所需的所有信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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