天天看點

python逐行讀取文本

一、使用open打開檔案後一定要記得調用檔案對象的close()方法。比如可以用try/finally語句來確定最後能關閉檔案。

二、需要導入import os

三、下面是逐行讀取檔案内容的三種方法:

1、第一種方法:

f = open("foo.txt")               # 傳回一個檔案對象  
line = f.readline()               # 調用檔案的 readline()方法  
while line:  
    print line,                   # 後面跟 ',' 将忽略換行符  
    #print(line, end = '')       # 在 Python 3 中使用  
    line = f.readline()   
f.close()           

2、第二種方法:

for line in open("foo.txt"):   
    print line           

四、一次性讀取整個檔案内容:

file_object = open('thefile.txt')  
try:  
     all_the_text = file_object.read()  
finally:  
     file_object.close()           
input = open('data', 'rb')           
chunk = input.read(100)