1.有一个jsonline格式的文件fifile.txt大小约为10K
def get_lines():
with open('file.txt', 'rb') as f:
return f.readlines()
if __name__ == '__main__':
for e in get_lines():
process(e) # 处理每一行数据
现在要处理一个大小为10G
的文件,但是内存只有
4G
,如果在只修改
get_lines
函数而其他代码保持不变的情况下,应该如何实现?需要考虑的问题都有那些?
def get_lines():
with open('file.txt', 'rb') as f:
for i in f:
yield i
最好设置下每次返回的行数,否则读取次数太多。
def get_lines():
l = []
with open('file.txt','rb') as f:
data = f.readlines(60000)
l.append(data)
yield l
Pandaaaa906提供的方法:
from mmap import mmap
def get_lines(fp):
with open(fp, "r+") as f:
m = mmap(f.fileno(), 0)
tmp = 0
for i, char in enumerate(m):
if char == b"\n":
yield m[temp: i+1].decode()
tmp = i + 1
if __name__ == "__main__":
for i in get_lines("fp_some_huge_file"):
print(i)
要考虑的问题有:内存只有4G
无法一次性读入
10G
文件,需要分批读入分批读入数据要记录每次读入数据的位置。分批每次读取数据的大小,太小会在读取操作花费过多时间。
https://stackoverflflow.com/questions/30294146/python-fastest-way-to-process-large-fifile
2.补充缺失的代码
def print_directory_contents(sPath):
"""
这个函数接收文件夹的名称作为输入参数
返回该文件夹中文件的路径
以及其包含文件夹中文件的路径
"""
import os
for s_child in os.listdir(s_path):
s_child_path = os.path.join(s_path, s_child)
if os.path.isdir(s_child_path):
print_directory_contents(s_child_path)
else:
print(s_child_path)