Python中以最快最少代码的读取文件内容方式
2019-03-19 11:15
399 查看
题目: 有一个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
相关文章推荐
- Python读取文件内容的三种常用方式及效率比较
- Java读取文件内容并输出的最简单的方式之一(只需三行代码)
- Python读取文件内容的三种方式并比较
- Python读取文件内容的三种常用方式及效率比较
- python读取文件:固定大小内容
- python 从两个配置文件读取数据,形成一个url思路代码
- Asp.Net读取并显示Excel文件中的内容(OleDb方式)
- PHP读取文件内容后清空文件示例代码
- PHP读取网页文件内容的实现代码(fopen,curl等)
- 读取excel文件内容代码
- CDays-3 习题二 (字典及文件读取练习)及相关内容解析。Python 基础教程
- java读取csv文件内容示例代码
- 基于COM组件方式读取Excel文件内容(C#版)
- Python 读取excle文件所有内容[xlrd模块]
- QFile 以追加的方式打开文件,读取内容为空的情况
- python 小实例3 with 简化文件的读取的代码
- python读取文件内容存入mysql
- 用ASP读取显示TXT文件内容的代码
- C语言中执行python代码或源程序文件(高级嵌入方式)
- 文件的读取操作、对话框的方式打开文件获取文件内容