文件操作的模式如下表:
創(chuàng)新互聯(lián)是專業(yè)的鎮(zhèn)寧網(wǎng)站建設(shè)公司,鎮(zhèn)寧接單;提供成都網(wǎng)站設(shè)計、網(wǎng)站制作、外貿(mào)營銷網(wǎng)站建設(shè),網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行鎮(zhèn)寧網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
使用 open 打開文件后一定要記得調(diào)用文件對象的 close() 方法。比如可以用 try/finally 語句來確保最后能關(guān)閉文件。
file_object = open(r'D:\test.txt') # 打開文件
try:
all_the_text = file_object.read( ) # 讀文件的全部內(nèi)容
finally:
file_object.close( ) # 關(guān)閉文件
print(all_the_text)
注:不能把 open 語句放在 try 塊里,因為當(dāng)打開文件出現(xiàn)異常時,文件對象 file_object 無法執(zhí)行 close() 方法。
讀文本文件方式打開文件
file_object = open(r'D:\test.txt', 'r') # 打開文件
#第二個參數(shù)默認為 r
file_object = open(r'D:\test.txt') # 打開文件
讀二進制文件方式打開文件
file_object= open(r'D:\test.txt', 'rb') # 打開文件
讀取所有內(nèi)容
file_object = open(r'D:\test.txt') # 打開文件
try:
all_the_text = file_object.read( )# 讀文件的全部內(nèi)容
finally:
file_object.close( ) # 關(guān)閉文件
print(all_the_text)
讀固定字節(jié)
file_object = open(r'D:\test.txt', 'rb') # 打開文件
try:
while True:
chunk = file_object.read(100) # 讀文件的100字節(jié)
if not chunk:
break
#do_something_with(chunk)
finally:
file_object.close( ) # 關(guān)閉文件
讀每行 readlines
file_object = open(r'D:\test.txt', 'r') # 打開文件
list_of_all_the_lines = file_object.readlines( ) #讀取全部行
print(list_of_all_the_lines)
file_object.close( ) # 關(guān)閉文件
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
file_object = open(r'D:\test.txt', 'r') # 打開文件
for line in file_object:
print(line)
file_object.close( ) # 關(guān)閉文件
寫文本文件方式打開文件
file_object= open('data', 'w')
寫二進制文件方式打開文件
file_object= open('data', 'wb')
追加寫文件方式打開文件
file_object= open('data', 'w+')
寫數(shù)據(jù)
'''
學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書!
'''
all_the_text="aaa\nbbb\nccc\n"
file_object = open(r'D:\thefile.txt', 'w') # 打開文件
file_object.write(all_the_text) #寫入數(shù)據(jù)
file_object.close( ) # 關(guān)閉文件
寫入多行
all_the_text="aaa\nbbb\nccc\n"
file_object = open(r'D:\thefile.txt', 'w')# 打開文件
file_object.writelines(all_the_text) #寫入數(shù)據(jù)
file_object.close( ) # 關(guān)閉文件
追加
file = r'D:\thefile.txt'
with open(file, 'a+') as f: # 打開文件
f.write('aaaaaaaaaa\n')
判斷文件是否存在:
import os.path
if os.path.isfile("D:\\test.txt"): # 判斷文件是否存在
print(":\\test.txt exists")
import os
os.getcwd() # 獲得當(dāng)前目錄
os.chdir("D:\\test.txt") # 改變當(dāng)前目錄
當(dāng)前標(biāo)題:Python教程:文件和讀寫的詳細教程
本文地址:http://m.kartarina.com/article38/dsogepp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、企業(yè)網(wǎng)站制作、自適應(yīng)網(wǎng)站、標(biāo)簽優(yōu)化、定制網(wǎng)站、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)