亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python文件操作,open讀寫文件,追加文本內(nèi)容實例

原創(chuàng) 2017-01-12 13:30:12 296
摘要:本篇文章主要介紹了Python文件操作,open讀寫文件,追加文本內(nèi)容,具有一定的參考價值,有需要的可以了解一下。1.open使用open打開文件后一定要記得調(diào)用文件對象的close()方法。比如可以用try/finally語句來確保最后能關(guān)閉文件。file_object = open('thefile.txt') try:  all_the_text

本篇文章主要介紹了Python文件操作,open讀寫文件,追加文本內(nèi)容,具有一定的參考價值,有需要的可以了解一下。

1.open使用open打開文件后一定要記得調(diào)用文件對象的close()方法。比如可以用try/finally語句來確保最后能關(guān)閉文件。

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

注:不能把open語句放在try塊里,因為當(dāng)打開文件出現(xiàn)異常時,文件對象file_object無法執(zhí)行close()方法。

2.讀文件讀文本文件input = open('data', 'r')

#第二個參數(shù)默認(rèn)為r
input = open('data')

讀二進(jìn)制文件input = open('data', 'rb')

讀取所有內(nèi)容file_object = open('thefile.txt')

try:
 all_the_text = file_object.read( )
finally:
 file_object.close( )


讀固定字節(jié)file_object = open('abinfile', 'rb')

try:
 while True:
 chunk = file_object.read(100)
 if not chunk:
 break
 do_something_with(chunk)
finally:
 file_object.close( )

讀每行l(wèi)ist_of_all_the_lines = file_object.readlines( )

如果文件是文本文件,還可以直接遍歷文件對象獲取每行:

for line in file_object:
 process line

3.寫文件寫文本文件output = open('data.txt', 'w')

寫二進(jìn)制文件output = open('data.txt', 'wb')

追加寫文件output = open('data.txt', 'a')

output .write("\n都有是好人") 
output .close( )

寫數(shù)據(jù)file_object = open('thefile.txt', 'w')

file_object.write(all_the_text)
file_object.close( )

更多關(guān)于Python文件操作,open讀寫文件,追加文本內(nèi)容實例請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!   


發(fā)佈手記

熱門詞條