python提供了很多种文件读取的方法,但是方法之间存在着读取速度的差异
1、.read(),.readline(),.readlines() :
python提供了.read(),.readline(),.readlines()三种读取文件的方法。每种方法接受一个变量以限制每次读取的数据量
使用.read()进行文件的读取时,python会对整个文件进行读取,通常想将文件的内容放入到一个字符串的中时使用,但是当文件的size很大,大于可用内存时,无法实现.read()处理(文件小于可用内存,但也很大时,会比其他两张方法占用的内存多)。
使用.readline()进行文件的读取时,python会调用该方法,每次读取出一行内容,当文件较大时,想占用相对少量内存进行文件读取时可使用.readline方法。
使用.readlines()进行文件读取时,python会读取整个文件的所有行,将其保存于一个列表(list)中,每行作为一个值传入列表中
split()方法:str.split(str="",num=string.count(str)).指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
Example
假设test.txt文件内容如下
First line
Second line
Third line
Fourth line
.read()
with open("test.txt") as file :
lines = file.read()
print(type(lines))
print(lines)
# Output result
<class 'str'> #字符串类型
First line
Second line
Third line
Fourth line
.readline()
f = open('test.txt','r')
result = list()
for line in open('test.txt'):
line = f.readline()
print (line)
result.append(line)
print (result)
print(type(line))
f.close()
# Output result
First line
['First line\n']
Second line
['First line\n', 'Second line\n']
Third line
['First line\n', 'Second line\n', 'Third line\n']
Fourth line
['First line\n', 'Second line\n', 'Third line\n', 'Fourth line']
<class 'str'>
.readlines()
f = open('test.txt','r')
lines = f.readlines()
print(lines)
print(type(lines))
for line in lines:
print (line)
f.close()
#output result
['First line\n', 'Second line\n', 'Third line\n', 'Fourth line']
<class 'list'>
First line
Second line
Third line
Fourth line
2、linecache模块
python中的linecache模块可以读取文件的行数以及内容,特定需要文件的行数以及内容的情况下可以使用linecache模块,平常情况下对于大文件读取的速率还可以
import linecache
with open("test.txt") as f :
for (num,line) in enumerate(f) :
print(num,line)
infos = linecache.getlines("test.txt")
print("Infos in test.txt:")
print(infos)
info = linecache.getline("test.txt",2)
print("The 2 line info in test.txt")
print(info)
#output result
0 First line
1 Second line
2 Third line
3 Fourth line
Infos in test.txt:
['First line\n', 'Second line\n', 'Third line\n', 'Fourth line\n']
The 2 line info in test.txt
Second line