Python四种逐行读取文件内容的方法
下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。方法一:readline函数
#-*- coding: UTF-8 -*-
f = open("./code.txt") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
#print line, # 在 Python 2中,后面跟 ',' 将忽略换行符
print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
优点:节省内存,不需要一次性把文件内容放入内存中
缺点:速度相对较慢
方法二:一次读取多行数据
代码如下:
#-*- coding: UTF-8 -*-
f = open("./code.txt")
while 1:
lines = f.readlines(10000)
if not lines:
break
for line in lines:
print(line)
f.close()
一次性读取多行,可以提升读取速度,但内存使用稍大, 可根据情况调整一次读取的行数
方法三:直接for循环
在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据
代码如下:
#-*- coding: UTF-8 -*-
for line in open("./code.txt"):
#print line, #python2 用法
print(line)
方法四:使用fileinput模块
import fileinput
for line in fileinput.input("./code.txt"):
print(line)
使用简单, 但速度较慢
热门日志
分类
- Django(4)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(32)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- shell(3)
- about(1)
- git(9)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(2)
- 架构(18)
- Vue(1)
- game(2)
- Html(6)
- Java(8)
- Mysql(37)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(72)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(48)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(12)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)