我想逐行读取一个大文件(>5GB),而不将其全部内容加载到内存中。我不能使用readlines(),因为它在内存中创建了一个非常大的列表。
当前回答
老派方法:
fh = open(file_name, 'rt')
line = fh.readline()
while line:
# do stuff with line
line = fh.readline()
fh.close()
其他回答
你所需要做的就是使用file对象作为迭代器。
for line in open("log.txt"):
do_something_with(line)
在最近的Python版本中使用上下文管理器更好。
with open("log.txt") as fileobject:
for line in fileobject:
do_something_with(line)
这也会自动关闭文件。
我不敢相信这能像@john-la-rooy的回答看起来那么简单。因此,我使用逐行读写重新创建了cp命令。这是疯狂的快。
#!/usr/bin/env python3.6
import sys
with open(sys.argv[2], 'w') as outfile:
with open(sys.argv[1]) as infile:
for line in infile:
outfile.write(line)
谢谢你!我最近已经转换到python 3,并对使用readlines(0)读取大文件感到沮丧。这就解决了问题。但是为了得到每一行,我必须做一些额外的步骤。每一行之前都有一个“b”,我猜这是二进制格式的。使用“decode(utf-8)”将其更改为ascii。
然后我必须在每行中间删除一个“=\n”。
然后我在新线处把线分开。
b_data=(fh.read(ele[1]))#endat This is one chunk of ascii data in binary format
a_data=((binascii.b2a_qp(b_data)).decode('utf-8')) #Data chunk in 'split' ascii format
data_chunk = (a_data.replace('=\n','').strip()) #Splitting characters removed
data_list = data_chunk.split('\n') #List containing lines in chunk
#print(data_list,'\n')
#time.sleep(1)
for j in range(len(data_list)): #iterate through data_list to get each item
i += 1
line_of_data = data_list[j]
print(line_of_data)
下面是Arohi代码中“打印数据”上方的代码。
blaze项目在过去6年里取得了长足的进展。它有一个简单的API,涵盖了pandas功能的一个有用子集。
dask。Dataframe内部负责分块,支持许多可并行操作,并允许您轻松地将切片导出回pandas,以便在内存中操作。
import dask.dataframe as dd
df = dd.read_csv('filename.csv')
df.head(10) # return first 10 rows
df.tail(10) # return last 10 rows
# iterate rows
for idx, row in df.iterrows():
...
# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()
# slice by column
df[df.my_field=='XYZ'].compute()
这个怎么样? 将文件划分为块,然后逐行读取,因为当您读取文件时,操作系统将缓存下一行。如果逐行读取文件,则不能有效利用缓存的信息。
相反,将文件划分为块,并将整个块加载到内存中,然后进行处理。
def chunks(file,size=1024):
while 1:
startat=fh.tell()
print startat #file's object current position from the start
fh.seek(size,1) #offset from current postion -->1
data=fh.readline()
yield startat,fh.tell()-startat #doesnt store whole list in memory
if not data:
break
if os.path.isfile(fname):
try:
fh=open(fname,'rb')
except IOError as e: #file --> permission denied
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except Exception as e1: #handle other exceptions such as attribute errors
print "Unexpected error: {0}".format(e1)
for ele in chunks(fh):
fh.seek(ele[0])#startat
data=fh.read(ele[1])#endat
print data