在python文件处理中使用readline()和行迭代器是否安全? [英] Is it safe to mix readline() and line iterators in python file processing?
问题描述
使用 readline()
读取一些行并且使用作为文件
中的行是安全的,它保证使用相同的文件位置?
通常,我想忽略第一行(标题),所以我这样做:
FI = open(myfile.txt)
FI.readline()#忽略第一行
FI中的行:
my_process(line)
FI.close()
这是否安全,是否保证在迭代行时使用相同的文件位置变量?解析方案
不,这是不安全的:
由于使用预读
缓冲区,将next()与其他
文件方法(如readline())结合使用,
不能正常工作。 >
您可以使用 next()
来跳过这里的第一行。你也应该测试 StopIteration
,如果文件是空的话,将会产生。
try:
header = next(f)
除了StopIteration之外还有e:
printFile is empty
为f:
#行做
Is it safe to read some lines with readline()
and also use for line in file
, and is it guaranteed to use the same file position?
Usually, I want to disregard the first line (headers), so I do this:
FI = open("myfile.txt")
FI.readline() # disregard the first line
for line in FI:
my_process(line)
FI.close()
Is this safe, i.e., is it guaranteed that the same file position variable is used while iterating lines?
No, 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.
You could use next()
to skip the first line here. You should also test for StopIteration
, which will be raised if the file is empty.
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文件处理中使用readline()和行迭代器是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!