python io操作有什么_Python笔记:文件IO操作
讀取文件
使用open()打開文件,文件不存在會拋出IOError錯誤。 try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
文件讀取完成一定要close(),為了保證在報錯的時候也能close(),這里用了finally語句,更簡潔的寫法是用with語句,會自動關閉。 with open('/path/to/file', 'r') as f:
print(f.read())
第二個參數r讀取文本文件,如果要讀取二進制文件使用rb。
讀取大文件
很小的文件直接使用read()讀取,大文件(超過1G)需要考慮使用分片或者單行讀取或者迭代之類的。
readlines讀取
with open(filename, 'rb') as f:
for line in f.readlines():
print(line.strip().decode())
read(size)分片讀取
使用read(chunk_size)指定大小去分片讀取文件。 with open(filePath, 'rb') as f:
while True:
chunk_data = f.read(chunk_size)
if not chunk_data:
break
print(chunk_data.strip().decode())
迭代行 with open(filename, 'rb') as f:
for line in f:
print(line.strip().decode())
strip():去掉末尾換行
decode():將二進制轉換成字符串
讀取非utf-8編碼
指定編碼,比如gbk。 f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') # 忽略錯誤
寫入文件
傳入標識符'w'或者'wb'表示寫文本文件或寫二進制文件: with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')
以'w'模式寫入文件時,如果文件不存在會新建,如果文件已存在,會直接覆蓋內容。
追加寫入
傳入'a'以append模式寫入。寫入中文時,指定編碼utf8防止亂碼。 with open('/Users/michael/test.txt', 'a', encoding='utf8') as f:
f.write('\n追加寫入:Hello, world!')
Python筆記:文件IO操作
更多精彩,敬請關注本博微信公眾號:hsu1943
總結
以上是生活随笔為你收集整理的python io操作有什么_Python笔记:文件IO操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 商品进销差价_商品进销差价概述
- 下一篇: easyexcel 在 设置标题_阿里开