python逐行讀取文本

1、使用open打開文件後必定要記得調用文件對象的close()方法。好比能夠用try/finally語句來確保最後能關閉文件。html

2、須要導入import ospython

3、下面是逐行讀取文件內容的三種方法:post

一、第一種方法:spa

[python] view plain copy

  

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

 


二、第二種方法:
  與第3種方法對比, 並不是一次性將所有的文件內容載入到內存裏,而是在迭代的時候,循環到哪一行纔將哪一行讀入內存。這裏涉及到一個新的概念-迭代器。
  第二種方法是文本文件讀取的最佳選擇,它簡單,且對任意大小的文件都有效,由於他不會一次性把整個文件都載入到內存裏,相反第三種方法存在內存壓力過大的問題。
for line in open("foo.txt"):   
    print line,    

 


三、第三種方法:
  
f = open("c:\\1.txt","r")   
lines = f.readlines()      #讀取所有內容 ,並以列表方式返回  
for line in lines   
    print line 

 

4、一次性讀取整個文件內容:.net

 

  

file_object = open('thefile.txt')  
try:  
     all_the_text = file_object.read()  
finally:  
     file_object.close()

 


5、區別對待讀取文本 和 二進制:

一、若是是讀取文本code

  
    讀文本文件  
    input = open('data', 'r')  
    #第二個參數默認爲r  
    input = open('data')  

 


二、若是是讀取二進制
 
  
input = open('data', 'rb')  

 

 讀固定字節htm

 

chunk = input.read(100)
相關文章
相關標籤/搜索