Python代码备忘

学习,练习,记录

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Python逐行读取文件内容

代码来源: Python参考手册

 

f = open("foo.txt")             # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
print line, # 后面跟 ',' 将忽略换行符
# print(line, end = '')   # 在 Python 3中使用
line = f.readline()

f.close()

也可以写成以下更简洁的形式

for line in open("foo.txt"):
print line,

更详细的文件按行读取操作可以参考:http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html

复制代码
1. 最基本的读文件方法:
?
# File: readline-example-1.py

file = open("sample.txt")

while 1:
line = file.readline()
if not line:
break
pass # do something
  一行一行得从文件读数据,显然比较慢;不过很省内存。
  在我的机器上读10M的sample.txt文件,每秒大约读32000行
2. 用fileinput模块
?
# File: readline-example-2.py

import fileinput

for line in fileinput.input("sample.txt"):
pass
  写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多……
3. 带缓存的文件读取
?
# File: readline-example-3.py

file = open("sample.txt")

while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
  这个方法真的更好吗?事实证明,用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!
————————————————————————————————————————————————————————————
  在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据:
?
# File: readline-example-5.py

file = open("sample.txt")

for line in file:
pass # do something
  而在Python 2.1里,你只能用xreadlines迭代器来实现:
?
# File: readline-example-4.py

file = open("sample.txt")

for line in file.xreadlines():
pass # do something
 
翻译自:http://hi.baidu.com/netspider_2007/blog/item/870354c753e4a71c9c163d64.html
复制代码




posted on   sysuoyj  阅读(163787)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示