【发布时间】:2020-07-03 04:45:10
【问题描述】:
我正在尝试将一个大文件 (1.1GB) 读入 python。文件中将有“这里”一词。我不知道我会在哪一行找到这个词。我将文件读成块。我的第一个块是直到单词“HERE”的数据。我的代码在这里运行良好。 (即在“HERE”之前存储数据并对其进行处理)但是我无法继续读取“HERE”之后的数据,因为“HERE”之后的数据太大。有什么办法可以让我逐行读取“这里”之后的数据? 我参考了参考:Reading a file until a specific character in python 我的代码是:
def each_chunk(stream, separator):
buffer = ''
while True: # until EOF
chunk = stream.read() # I propose 4096 or so
if not chunk: # EOF?
yield buffer
break
buffer += chunk
while True: # until no separator is found
try:
part, buffer = buffer.split(separator, 1)
except ValueError:
break
else:
yield part
def first_chunk(chunk):
.... #my function
def chunk_after(data_line_by_line):
.... #my function
global This_1st_chunk
This_1st_chunk=True
myFile= open(r"C:\Users\Mavis\myFile.txt","r")
for chunk in each_chunk(myFile, separator='HERE'):
if This_1st_chunk:
first_chunk(chunk)
This_1st_chunk=False
elif not This_1st_chunk:
print('*******after 1st chunk*********')
#**I WANT TO READ THE DATA LINE BY LINE HERE.**
chunk_after(data_line_by_line)
【问题讨论】: