python中讀取文件的三種方法read(),readline(),readlines()python
測試文件tb.txt文件的內容:ide
Oracle測試
MySQLspa
PostgreSQL內存
Redis字符串
MongoDBget
readit
返回的是字符串類型,默認讀取文件的所有內容;io
file1 = open('tb.txt', 'r') content = file1.read() file1.close print(content) print(type(content)) 輸出結果: Oracle MySQL PostgreSQL Redis MongoDB <type 'str'>
readlinefunction
返回的是字符串類型,默認每次只加載讀取一行;
file1 = open('tb.txt', 'r') content1 = file1.readline() file1.close print(type(content1)) print(content1) 輸出結果: <type 'str'> Oracle
from __future__ import print_function file1 = open('tb.txt', 'r') content = file1.readline() print(type(content)) while content: print(content, end='') content = file1.readline() file1.close 輸出結果: <type 'str'> Oracle MySQL PostgreSQL Redis MongoDB
readlines
返回的是list類型,默認返回的是文件中所有內容;
file1 = open('tb.txt', 'r') content = file1.readlines() file1.close print(type(content)) print(content) 輸出結果: <type 'list'> ['Oracle\n', 'MySQL\n', 'PostgreSQL\n', 'Redis\n', 'MongoDB']
linecache.getline
返回的是list類型,指定返回某一行;
import linecache content = linecache.getline('tb.txt', 4) print(type(content)) print(content) 輸出結果: <type 'str'> Redis
總結
read和readlines須要把整個大文件加載到內存中,因此操做大文件比較慢;
而readline是每次只加載一行,佔用內存小,因此操做大文件的時候比較快;
linecache.getline能夠指定操做的行,效率也還能夠;