题目: 有一个jsonline格式的文件file.txt大小约为10K
普通方法1:
def get_lines():
with open("file.txt", "rb") as f:
return f.readlines()
if __name__ == '__main__':
for e in get_lines():
print(e)
"""
结果:
b'this is the first\n'
b'this is the second \n'
b'this is the third\n'
b'this is the four\n'
普通方法2:
for line in open("file.txt"):
print(line, end=""
"""
结果为:
this is the first
this is the second
this is the third
this is the four
"""
现在需要处理一个大小为10G文件,但是内存只有4G,如果在只修改get_lines 函数而其他代码保持不变的情况下,应该如何实现?需要考虑的问题都有那些?
# 除了使用f.readline()可以胜任,也可以借助线程来执行。
def get_lines():
for line in open("file.txt"):
print(type(line))
yield line # line相当于f.readline(), 为str类型
if __name__ == '__main__':
for i in get_lines():
print(i, end="")
"""
结果为:
<class 'str'>
this is the first
<class 'str'>
this is the second
<class 'str'>
this is the third
<class 'str'>
this is the four