Python按行读取文件

简介:

1:readline()

复制代码
file = open("sample.txt") 
while 1:
    line = file.readline()
    if not line:
        break
    pass # do something
file.close()
复制代码

一行一行得从文件读数据,显然比较慢;

不过很省内存;

测试读10M的sample.txt文件,每秒大约读32000行;

2:fileinput

import fileinput 
for line in fileinput.input("sample.txt"):
    pass

写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多;

3:readlines()

复制代码
file = open("sample.txt") 
while 1:
    lines = file.readlines(100000)
    if not lines:
        break
    for line in lines:
        pass # do something
file.close()
复制代码

用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!

4:文件迭代器

每次只读取和显示一行,读取大文件时应该这样:

file = open("sample.txt") 
for line in file:
    pass # do something
file.close()



相关文章
|
13天前
|
存储 Python
Python文件编码概念详解
Python文件编码概念详解
17 1
|
6天前
|
Java Python
Python的文件对象
【6月更文挑战第5天】
15 4
|
18小时前
|
数据可视化 Python
使用Python进行数据可视化(三、处理csv文件(二))
使用Python进行数据可视化(三、处理csv文件(二))
|
18小时前
|
存储 数据可视化 Python
使用Python进行数据可视化(三、处理csv文件)
使用Python进行数据可视化(三、处理csv文件)
|
1天前
|
存储 数据安全/隐私保护 计算机视觉
python文件对象读写二进制文件
【6月更文挑战第7天】
20 6
|
1天前
|
Python
python文件对象写入文件
【6月更文挑战第7天】
11 6
|
1天前
|
Python
python文件对象读取文件
【6月更文挑战第7天】
8 4
|
2天前
|
数据库连接 Python
python的文件对象使用with语句
【6月更文挑战第6天】
9 4
|
2天前
|
Python
python的文件对象的方法
【6月更文挑战第6天】
9 3
|
2天前
|
Python
python的文件对象打开文件
【6月更文挑战第6天】
13 4