日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python中文本文件r_Python如何读写文本文件

發布時間:2025/3/12 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中文本文件r_Python如何读写文本文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

展開全部

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

file_object = open('thefile.txt')

try:

all_the_text = file_object.read( )

finally:

file_object.close( )

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

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

#第二個參數默認為r

input = open('data')

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

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

try:

all_the_text = file_object.read( )

finally:

file_object.close( )

讀固定字節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( )

讀每行list_of_all_the_lines = file_object.readlines( )

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

for line in file_object:

process line

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

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

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

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

output .close( )

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

file_object.write(all_the_text)

file_object.close( )

本回答由電腦網絡分類達人 郭強推薦

已贊過

已踩過<

你對這個回答的評價是?

評論

收起

總結

以上是生活随笔為你收集整理的python中文本文件r_Python如何读写文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。