我在每个目录中有多个目录和许多文件,我想迭代它们中的每一个。我还想只读取每个文件的5th
行,因此忽略前四行。当我运行脚本而不忽略尝试忽略第一个4
行时,它运行正常。这是代码:
import os
#find the present working directory
pwd=os.path.dirname(os.path.abspath(__file__))
#find all the folders in the present working directory.
dirs = [f for f in os.listdir('.') if os.path.isdir(f)]
for directory in dirs:
os.chdir(os.path.join(pwd, directory));
chd_dir = os.path.dirname(os.path.abspath(__file__))
files = [ fl for fl in os.listdir('.') if os.path.isfile(fl) ]
print files
for f in files:
f_obj = open(os.path.join(chd_dir, f), 'r')
for i in xrange(0,4): #ignore the first 4 lines
f_obj.next()
s=f_obj.readline()
print s
f_obj.close()
此脚本出现以下错误:
ValueError: Mixing iteration and read methods would lose data
我不明白为什么python认为我会丢失一些数据而且我也想知道修复它的工作以及它为什么修复它。
答案 0 :(得分:2)
您可以使用.next()
方法reed第5行:
s = f_obj.next()
文件迭代方法使用缓冲来保持高效,并且该缓冲区不与.readline()
和文件对象的其他读取方法共享。因此,在混合迭代和读取方法时,您将错过数据。
来自.next()
method documentation:
为了使for循环成为循环文件行的最有效方式(一种非常常见的操作),
next()
方法使用隐藏的预读缓冲区。使用预读缓冲区的结果是,将next()
与其他文件方法(如readline()
)组合不起作用。
您也可以使用.next()
来电替换.readline()
来电,只需保持一致并使用其中一种。