眾所周知在python中讀取文件常用的三種方法:read(),readline(),readlines(),今天看項目是又忘記他們的區別了。以前看書的時候覺得這東西很簡單,一眼掃過,待到用時卻也只知道有這么幾個方法,不懂得它的原理與用法。也許吧,沒有永遠的記憶,況且根本沒有用心去記它。話不多說,來一起看看詳細的介紹:
假設a.txt
一、read([size])方法
read([size])
方法從文件當前位置起讀取size個字節,若無參數size,則表示讀取至文件結束為止,它范圍為字符串對象
f = open("a.txt") lines = f.read() print lines print(type(lines)) f.close()
輸出結果:
Hello Welcome What is the fuck... <type 'str'> #字符串類型
二、readline()方法
從字面意思可以看出,該方法每次讀出一行內容,所以,讀取時占用內存小,比較適合大文件,該方法返回一個字符串對象。
1
2
3
4
5
6
7
|
f
=
open
(
"a.txt"
)
line
=
f.readline()
print
(
type
(line))
while
line:
print
line,
line
=
f.readline()
f.close()
|
輸出結果:
<type 'str'> Hello Welcome What is the fuck...
三、readlines()方法讀取整個文件所有行,保存在一個列表(list)變量中,每行作為一個元素,但讀取大文件會比較占內存
f = open("a.txt") lines = f.readlines() print(type(lines)) for line in lines: print line, f.close()
輸出結果:
1 <type 'list'> 2 Hello 3 Welcome 4 What is the fuck...
四、linecache模塊
當然,有特殊需求還可以用linecache模塊,比如你要輸出某個文件的第n行:
1
2
3
|
# 輸出第2行
import linecache
text
=
linecache.getline(‘a.txt',
2
)
print
text,
|