Django之中介軟體
阿新 • • 發佈:2020-10-27
python的檔案操作
檔案讀寫
檔案讀的操作步驟
- 開啟檔案
- 操作檔案描述 讀/寫
- 關閉檔案(易忘)
檔案開啟
file = open("檔案路徑以及檔名","開啟模式"
檔案關閉
file.close() ------------------ ## 讀 ```python # 第一步,開啟檔案(以只讀模式) file = open("book.txt","r") # 第二步,讀取檔案 file.read() # 第三步,關閉檔案 file.close()
遍歷開啟檔案中的每一行
with open("book.txt","r",encoding="UTF-8") asb for i in b.readlines(): print(i)
- read() :括號內可以寫數字,表示的是讀取多少個字元,預設讀取所有
- readline:一次讀取檔案的一行內容
- readlines:一次讀取檔案的所有內容,一行內容為一個元素,以列表的形式展示
檔案的開啟模式
寫
# 第一步,開啟檔案(以只寫模式) file = open("book.txt","w") # 第二步,寫入檔案 file.write("內容") # 第三步,關閉檔案 file.close()
- 寫入內容會依次追加到最後
生成備份檔案
file_Name = input("請輸入要備份的檔名") file_1 = open(file_Name,"r") # index 是找到file_name中‘.’的索引值 index = file_Name.rfind('.') if index > 0: new_name = file_Name[:index]+"備份"+file_Name[index:] else: new_name = file_Name+"備份" file_2 = open(new_name,"w") count = file_1.read() file_2.write(count) file_1.close() file_2.close()
獲取檔案當前的讀寫位置
file.tell()
檔案下表從0開始,檔案開啟時,指標在0
file = open("bbb.txt", encoding="utf-8") print(file.tell()) content = file.read(15) print(content) print(file.tell()) file.close()
檢視與修改檔案的讀寫位置,seek(offset,from)
- offest:偏移的位元組數
- from:從哪開始,三個選擇
0:從檔案開始,預設
1:從檔案的當前位置開始,檔案以非二進位制的模式開啟,只能跳轉0
2:檔案末尾開始
file = open(("aaa.txt"),"r+") print(file.tell()) file.seek(5,0) print(file.tell()) print(file.read(5)) print(file.tell()) print(file.seek(0,1)) # 從檔案當前位置偏移0個位元組 print(file.seek(5,1)) # 從檔案當前位置偏移5個位元組 file.close()
刪除指定的檔案
- 需要引入os模組
格式: os.remove("檔名")
import os os.remove("bbb.tst")
pickle.dump方法和pickle.load方法的運用
import pickle class Person: def __init__(self,name,age,sex,id): self.name = name self.age = age self.sex = sex self.id = id def learn(self): print("我喜歡學習Python語言") # # zs = Person("張三", 23, "男", 12345678) ls = Person("里斯", 20, "男", 1234567890) print(zs.age) dict_1 = {} dict_1[zs.id] = zs dict_1[ls.id] = ls print(dict_1[zs.id]) # 這裡輸出的記憶體地址 print(dict_1[ls.id]) # 將字典儲存至文字檔案中(.txt) file = open("E:\\project\\rotect.txt", "wb") # 這裡不支援encoding="utf-8" # write只能寫入字串內容,不能直接存字典 pickle.dump(dict_1,file) file.close() # file = open("E:\\project\\rotect.txt", "rb") # 這裡不支援encoding="utf-8" # pick.load 用於讀出資料 count = pickle.load(file) dict_2 = count print(type(dict_2), dict_2)