1、使用open打開文件後必定要記得調用文件對象的close()方法。好比能夠用try/finally語句來確保最後能關閉文件。html
2、須要導入import ospython
3、下面是逐行讀取文件內容的三種方法:post
一、第一種方法:spa
f = open("foo.txt") # 返回一個文件對象 line = f.readline() # 調用文件的 readline()方法 while line: print line, # 後面跟 ',' 將忽略換行符 #print(line, end = '') # 在 Python 3 中使用 line = f.readline() f.close()
for line in open("foo.txt"): print line,
4、一次性讀取整個文件內容:.net
file_object = open('thefile.txt') try: all_the_text = file_object.read() finally: file_object.close()
一、若是是讀取文本code
input = open('data', 'rb')
讀固定字節htm
chunk = input.read(100)