Python open读写文件实现脚本
生活随笔
收集整理的這篇文章主要介紹了
Python open读写文件实现脚本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? Python中文件操作可以通過open函數,這的確很像C語言中的fopen。通過open函數獲取一個file object,
然后調用read(),write()等方法對文件進行讀寫操作。
1.open
使用open打開文件后一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最后能關閉文件。
<span style="font-size:18px;">file_object = open('thefile.txt') try:all_the_text = file_object.read( ) finally:file_object.close( ) </span>注:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。
2.讀文件
讀文本文件
<span style="font-size:18px;">input = open('data', 'r') #第二個參數默認為r input = open('data') </span>讀二進制文件
input = open('data', 'rb')
讀取所有內容
<span style="font-size:18px;"> file_object = open('thefile.txt') try:all_the_text = file_object.read( ) finally:file_object.close( )</span>讀固定字節
<span style="font-size:18px;">file_object = open('abinfile', 'rb') try:while True:chunk = file_object.read(100)if not chunk:breakdo_something_with(chunk) finally:file_object.close( ) </span>
讀每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
??? process line
3.寫文件
寫文本文件
output = open('data', 'w')
寫二進制文件
output = open('data', 'wb')
追加寫文件
output = open('data', 'w+')
寫數據
<span style="font-size:18px;">file_object = open('thefile.txt', 'w') file_object.write(all_the_text) file_object.close( ) </span>寫入多行
file_object.writelines(list_of_text_strings)
注意,調用writelines寫入多行在性能上會比使用write一次性寫入要高
總結
以上是生活随笔為你收集整理的Python open读写文件实现脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 字符串操作方法大全
- 下一篇: 集合set