Python中read()、readline()和readlines()的用法簡單案例
阿新 • • 發佈:2019-02-14
首先我們先建立一個測試檔案,test.txt
1.read() 用法:
從檔案當前位置起讀取size個位元組,若無引數size,則表示讀取至檔案結束為止,它範圍為字串物件。
# 開啟含中文的文字
file=open("test.txt",encoding='utf8')
# 讀取前面5個字元
str=file.read(5)
print(str)
# 讀取全文,要記住,現在是從第五個字元後面開始讀取
str2=file.read()
print(str2)
執行結果:
2.readline()用法:
該方法每次讀出一行內容,所以,讀取時佔用記憶體小,比較適合大檔案,該方法返回一個字串物件。
# 開啟含中文的文字 file=open("test.txt",encoding='utf8') # 按行讀取 while True: str=file.readline() print(str) # 讀取完,迴圈結束 if len(str)==0: break file.close()
執行結果:
3.readlines()用法:
讀取整個檔案所有行,儲存在一個列表(list)變數中,每行作為一個元素,但讀取大檔案會比較佔記憶體。
# 開啟含中文的文字
file=open("test.txt",encoding='utf8')
str=file.readlines()
print(str)
file.close()
執行結果:
如果需要把換行符'\n'去掉,只需要改成:
# 開啟含中文的文字 file=open("test.txt",encoding='utf8') str=file.readlines() for line in str: print(line.strip('\n')) file.close()