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

2024-09-28 23:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些文本文件包含7行当我试图打印第3行和第4行使用以下代码,它打印第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

但是,当我运行以下任何一个代码时,我没有得到任何错误

代码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

代码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

好像我不能同时读两行字。这太令人沮丧了


Tags: 代码inforifoslinerootfiles
2条回答

方法readlines()读取文件中的所有行,直到到达EOF(文件结尾)。 “cursor”位于文件的末尾,随后对readlines()的调用不会产生任何结果,因为EOF是直接找到的

因此,在line_3 = fRead.readlines()[3]之后,您已经使用了整个文件,但只存储了第四个(!)文件的行(如果您从1开始计算行数)

如果你这样做了

all_lines =  fRead.readlines()
line_3 = all_lines[3]
line_4 = all_lines[4]

您只读取了一次文件并保存了所需的所有信息

如文件所述:

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.

用完所有行后,对readlines的下一个调用将为空

更改函数以将结果存储在临时变量中:

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

相关问题 更多 >