我有一些文本文件包含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
好像我不能同时读两行字。这太令人沮丧了强>
方法
readlines()
读取文件中的所有行,直到到达EOF(文件结尾)。 “cursor”位于文件的末尾,随后对readlines()
的调用不会产生任何结果,因为EOF是直接找到的因此,在
line_3 = fRead.readlines()[3]
之后,您已经使用了整个文件,但只存储了第四个(!)文件的行(如果您从1开始计算行数)如果你这样做了
您只读取了一次文件并保存了所需的所有信息
如文件所述:
用完所有行后,对
readlines
的下一个调用将为空更改函数以将结果存储在临时变量中:
相关问题 更多 >
编程相关推荐