在python中讀取文件常用的三種方法:read(),readline(),readlines()
準備
假設a.txt的內(nèi)容如下所示:
Hello
Welcome
What is the fuck...
一、read([size])方法
read([size])方法從文件當前位置起讀取size個字節(jié),若無參數(shù)size,則表示讀取至文件結(jié)束為止,它范圍為字符串對象
f = open("a.txt")
lines = f.read()
print lines
print(type(lines))
f.close()
輸出結(jié)果:
Hello
Welcome
What is the fuck...
<type 'str'> #字符串類型
二、readline()方法
從字面意思可以看出,該方法每次讀出一行內(nèi)容,所以,讀取時占用內(nèi)存小,比較適合大文件,該方法返回一個字符串對象。
f = open("a.txt")
line = f.readline()
print(type(line))
while line:
print line,
line = f.readline()
f.close()
輸出結(jié)果:
<type 'str'>
Hello
Welcome
What is the fuck...
三、readlines()方法
readlines()方法讀取整個文件所有行,保存在一個列表(list)變量中,每行作為一個元素,但讀取大文件會比較占內(nèi)存。
f = open("a.txt")
lines = f.readlines()
print(type(lines))
for line in lines:
print line,
f.close()
#Python學習交流群:711312441
輸出結(jié)果:
<type 'list'>
Hello
Welcome
What is the fuck...
四、linecache模塊
當然,有特殊需求還可以用linecache模塊,比如你要輸出某個文件的第n行:文章來源:http://www.zghlxwxcb.cn/news/detail-839370.html
# 輸出第2行
text = linecache.getline(‘a(chǎn).txt',2)
print text,
對于大文件效率還可以。文章來源地址http://www.zghlxwxcb.cn/news/detail-839370.html
到了這里,關(guān)于Python中read()、readline()和readlines()三者間的區(qū)別和用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!