gpt4 book ai didi

python - 在 python 文件处理中混合 readline() 和行迭代器是否安全?

转载 作者:IT老高 更新时间:2023-10-28 21:12:07 25 4
gpt4 key购买 nike

使用 readline() 读取某些行并使用 for line in file 是否安全,是否保证使用相同的文件位置?

通常,我想忽略第一行(标题),所以我这样做:

FI = open("myfile.txt")
FI.readline() # disregard the first line
for line in FI:
my_process(line)
FI.close()

这是否安全,即是否保证在迭代行时使用相同的文件位置变量?

最佳答案

不,it isn't safe :

As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

您可以使用 next() 跳过此处的第一行。您还应该测试 StopIteration,如果文件为空,则会引发该问题。

with open('myfile.txt') as f:
try:
header = next(f)
except StopIteration as e:
print "File is empty"
for line in f:
# do stuff with line

关于python - 在 python 文件处理中混合 readline() 和行迭代器是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com