檔案操作的模式
檔案操作的模式如下表:

1. open 打開檔案
使用 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() 方法,
2. 讀檔案
讀文本檔案方式打開檔案
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( ) # 關閉檔案
3. 寫檔案
寫文本檔案方式打開檔案
file_object= open('data', 'w')
寫二進制檔案方式打開檔案
file_object= open('data', 'wb')
追加寫檔案方式打開檔案
file_object= open('data', 'w+')
寫資料
'''
學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和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") # 改變當前目錄
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/502894.html
標籤:Python
