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