Python 有时不会读取整个文件
Python will Sometimes Not Read in Entire File
我在 unix 服务器上使用了 python 2.7 程序,该程序读取包含两种信息的 ASCII 文件并处理该信息。我已将此过程放入一个函数中,该函数基本上执行以下操作:
def read_info()
f = open(file_name, 'rb')
f_enumerator = enumerate(f, start=1)
for i, line in f_enumerator:
process_info
process_last_info
当从我的主程序在文件上调用此函数时,它会在一行中途的一个看似任意的点停止,直到输入文件的末尾,而当从同一文件的简单包装器调用该函数时输入文件它正确读取整个文件。
我在这里尝试了其中一种解决方案:Python Does Not Read Entire Text File,文件以二进制形式读入,但这并没有解决问题。
那里的另一个解决方案(分块读取文件)会有问题,因为我试图在特定于行的基础上解析文件,并且读取文本块需要更多的解析。
我愿意这样做,除非问题的间歇性向我暗示可能还有其他解决方案?
def read_info():
with open(file_name, 'rb') as f:
for i, a_line in enumerate(f,1): #a_line must end with a newline
process_info(a_line,i)
# you have processed whole file here so no need for `process_last_info`
使用 with
将确保您的文件句柄已关闭(您尤其应该在写入文件时这样做,但实际上这始终是一个好习惯)...
关于来自 OP 的更多信息,我相信发电机将是解决他的问题的理想方法
def data_gen(f):
header = None
lines = []
for line in f:
if line.startswith(">"): #header
if header is not None: #if its not the first line basically
yield header,lines
header = line #set the header
lines = [] #reinitialize lines
else:
lines.append(line)
yield header,lines # the last section
def read_info(fname):
with open(fname,"rb") as f:
for header,lines in data_gen(f):
process(header,lines)
作为 O.P。发现,问题是该文件先前已在同一程序上创建,但在尝试读取之前未正确刷新或关闭。
进一步思考,我意识到这是因为我在程序中较早地创建了文件并且没有关闭文件句柄,因此这可能是一个缓冲问题。提前关闭文件解决了这个问题。
建议我使用 "with" 语法写入文件:
with open(file_name, 'w') as f:
do foo
这确实可以防止我忘记关闭文件,从而避免了这个问题。
我在 unix 服务器上使用了 python 2.7 程序,该程序读取包含两种信息的 ASCII 文件并处理该信息。我已将此过程放入一个函数中,该函数基本上执行以下操作:
def read_info()
f = open(file_name, 'rb')
f_enumerator = enumerate(f, start=1)
for i, line in f_enumerator:
process_info
process_last_info
当从我的主程序在文件上调用此函数时,它会在一行中途的一个看似任意的点停止,直到输入文件的末尾,而当从同一文件的简单包装器调用该函数时输入文件它正确读取整个文件。
我在这里尝试了其中一种解决方案:Python Does Not Read Entire Text File,文件以二进制形式读入,但这并没有解决问题。 那里的另一个解决方案(分块读取文件)会有问题,因为我试图在特定于行的基础上解析文件,并且读取文本块需要更多的解析。
我愿意这样做,除非问题的间歇性向我暗示可能还有其他解决方案?
def read_info():
with open(file_name, 'rb') as f:
for i, a_line in enumerate(f,1): #a_line must end with a newline
process_info(a_line,i)
# you have processed whole file here so no need for `process_last_info`
使用 with
将确保您的文件句柄已关闭(您尤其应该在写入文件时这样做,但实际上这始终是一个好习惯)...
关于来自 OP 的更多信息,我相信发电机将是解决他的问题的理想方法
def data_gen(f):
header = None
lines = []
for line in f:
if line.startswith(">"): #header
if header is not None: #if its not the first line basically
yield header,lines
header = line #set the header
lines = [] #reinitialize lines
else:
lines.append(line)
yield header,lines # the last section
def read_info(fname):
with open(fname,"rb") as f:
for header,lines in data_gen(f):
process(header,lines)
作为 O.P。发现,问题是该文件先前已在同一程序上创建,但在尝试读取之前未正确刷新或关闭。
进一步思考,我意识到这是因为我在程序中较早地创建了文件并且没有关闭文件句柄,因此这可能是一个缓冲问题。提前关闭文件解决了这个问题。
建议我使用 "with" 语法写入文件:
with open(file_name, 'w') as f:
do foo
这确实可以防止我忘记关闭文件,从而避免了这个问题。