17 - 文件讀寫📄目錄1 基礎操作1.1 文件操作1.2 文件對象的方法1.3 屬性1.4 操作範例2 文件讀寫2.1 read(n)2.2 readline()2.2.1 for循環讀取(不用readline()2.3 readlines()2.2.1 for循環讀取2.4 訪問模式2.4.1 r:只讀模式(默認)2.4.2 w:只寫模式2.4.3 +:可以同時讀寫某個文件2.4.4 a:追加模式2.5 文件定位操作2.5.1 寫入後讀取方式一:更改訪問模式(取巧)2.5.2 文件定位操作:tell()和seek()3 編碼格式3.1 with open3.2 encoding3.3 案例:圖片複制 rb&wb4 目錄常用操作4.1 文件重命名 os.rename(舊名字, 新名字)4.2 刪除文件 os.remove()4.3 創建文件夾 os.mkdir()4.4 刪除文件夾 os.rmdir()4.5 獲取當前目錄 os.getcwd()4.6 獲取目錄列表 os.listdir()導航連結:
文件就是存儲在某種長期儲存設備上的一段數據,分為文本文件和二進制文件(如圖片)
三步驟
打開文件
讀寫文件(可以不讀寫)
關閉文件
open():創建一個file對象,默認以檢視模式打開
read(n):n表示從文件中讀取數據的長度,沒有傳n值就默認一次性讀取文件所有內容
write():將指定內容寫入文件
close():關閉文件
文件名.name:返回要打開的文件的文件名,可以包含文件的具體路徑
文件名.mode:返回文件的訪問模式
文件名.closed:檢測文件是否關閉,關閉就返回True

在本文件夾(/PyPractice)建立一個test.txt文件,包含以下內容:
xxxxxxxxxxValantineVictoriaTheodosia
xxxxxxxxxx# 1. 打開文件f = open('test.txt')print(f.name) # 文件名print(f.mode) # 文件訪問模式print(f.closed) # 文件未關閉,顯示False# 2. 關閉文件f.close()print(f.closed)輸出結果:
xxxxxxxxxxtest.txtrFalseTruen表示從文件中讀取數據的長度,沒有傳n值或者傳的是負數就默認一次性讀取文件所有內容

沿用test.txt
xxxxxxxxxxf = open('../PyPractice/test.txt')# f = open(r'C:\Users\Bearbelly\Desktop\test.txt') # \是轉義字符,所以可以加上r''來防止錯誤print(f)print(f.read(5)) # 設置為多少,讀取多少。這裡最多讀取5個數據print(f.name) # 輸入絕對位置,顯示絕對位置;輸入相對位置,顯示相對位置f.close()輸出結果:
xxxxxxxxxx<_io.TextIOWrapper name='../PyPractice/test.txt' mode='r' encoding='UTF-8'>Valan../PyPractice/test.txt一次讀取一行內容,方法執行完,會把文件指針移到下一行,準備再次讀取

xxxxxxxxxxf = open('test.txt')# print(f.readline()) # 讀取第一行,同時換行# print(f.readline()) # 讀取第二行,同時換行(所以輸出顯示與第一行隔了一個空行)while True: text = f.readline() # 讀取不到內容,就要退出循環 if not text: break print(text)f.close()輸出結果:
xxxxxxxxxxValantine
Victoria
Theodosia

xxxxxxxxxxf = open('test.txt')for i in f: print(i, end = '') # print函數後預設自動換行,但txt本身已經換了一行,相當於換兩行,end = ''減少換行f.close()輸出結果:
xxxxxxxxxxValantineVictoriaTheodosia按照行的方式把文件內容一次件讀取,返回一個列表,每一行的數據就是列表中的一個元素

xxxxxxxxxxf = open('test.txt')text = f.readlines()print(text, type(text))f.close()輸出結果:
xxxxxxxxxx['Valantine\n', 'Victoria\n', 'Theodosia'] <class 'list'>
xxxxxxxxxxf = open('test.txt')text = f.readlines()for i in text: print(i, end = '')f.close()輸出結果:
xxxxxxxxxxValantineVictoriaTheodosia| 模式 | 可做操作 | 若文件不存在 | 是否覆蓋 |
|---|---|---|---|
| r | 只能讀 | 報錯 | / |
| r+ | 可讀可寫 | 報錯 | 是 |
| w | 只能寫 | 創建 | 是 |
| w+ | 可讀可寫 | 創建 | 是 |
| a | 只能寫 | 創建 | 否,追加寫 |
| a+ | 可讀可寫 | 創建 | 否,追加寫 |
❗ 文件必須存在,不存在就會報錯

⚠️⚠️ r模式只可讀、不可寫
xxxxxxxxxxfile = open('test.txt', 'r')print(file.read())file.write('...')file.close()輸出結果:
xxxxxxxxxxTraceback (most recent call last): File "/Users/Myname/Documents/Coding/PyCharm/PyPractice/py35.py", line 81, in <module> file.write('...')io.UnsupportedOperation: not writableValantineVictoriaTheodosia文件存在就會先清空內容,再寫入添加內容;文件不存在就創建新文件

xxxxxxxxxxfile = open('test01.txt', 'w')file.write('Antonio\nBenny\nCecelia')file.close()test01.txt顯示:
xxxxxxxxxxAntonioBennyCecelia使用+會影響文件的讀寫效率,開發過程中更多時候會以只讀、只寫的方式來操作文件
r+:可讀寫文件,文件不存在就會報錯
w+:先寫再讀,文件存在就重新編輯文件,不存在就創建新文件

xxxxxxxxxxf = open('test01.txt', 'w+')print(f.read()) # 先讀取就讀不到(先寫再讀原則)f.write('extra name') # 會把原有內容覆蓋print(f.read()) # 光標移到文件最後,所以也讀不到,需要進行文件定位f.close()test01.txt顯示:
xxxxxxxxxxextra name不存在就創建新文件進行寫入,存在則在原有內容的基礎上添加新內容

xxxxxxxxxxf = open('test01.txt', 'a')f.write('\nAntonio')f.close()test01.txt顯示:
xxxxxxxxxxextra nameAntonio💡 重要概念:文件指針
👉🏻 標記從哪一個位置開始讀取數據

xxxxxxxxxxf = open('test01.txt', 'w+')f.write('Dennis')f.close()f = open('test01.txt', 'r')print(f.read())f.close()輸出結果:
xxxxxxxxxxDennistell()和seek()tell():顯示文件內當前位置,即文件指針當前位置
seek(offset, whence):移動文件讀取指針到指定位置
offset:偏移量,表示要移動的字節數
whence:超始位置,表示移動字節的參考位置
默認值是0,表示文件開頭作為參考位置
1代表當前位置作為參考位置
2代表將文件結尾位為參考位置
例子:seek(0,0)就會把文件指針移到文件開頭

xxxxxxxxxxf = open('test01.txt', 'w+')f.write('hello world')pos = f.tell()print(f'當前文件指針所在位置:{pos}') # 定位f.seek(0,0)pos2 = f.tell() # 不能用同一變量名print(f'移動後文件指針所在位置:{pos2}')print(f.read())f.close()或者:
xxxxxxxxxxf = open('test01.txt', 'w+')f.write('hello world')print(f'當前文件指針所在位置:{f.tell()}') # 定位f.seek(0,0)print(f'移動後文件指針所在位置:{f.tell()}')print(f.read())f.close()輸出結果:
xxxxxxxxxx當前文件指針所在位置:11移動後文件指針所在位置:0hello worldwith open作用:代碼執行完,系統會自動調用f.close()方法,可以省略文件關閉步驟

xxxxxxxxxxwith open('test01.txt', 'w') as f: # f是文件對象 f.write('"with open" mode') # 以"with open" mode覆蓋原有內容 print(f.closed)print(f.closed)輸出結果:
xxxxxxxxxxFalseTrue
xxxxxxxxxxwith open('test01.txt', 'w', encoding='utf-8') as f: f.write('hello world!\n這裡有中文!')with open('test01.txt', encoding='utf-8') as f: # 某些電腦不一定能識別所有字符,因此最好都加上utf-8 print(f.read())輸出結果:
xxxxxxxxxxhello world!這裡有中文!rb&wb
xxxxxxxxxx"""1. 讀取圖片圖片是一個二進制文件,想要寫入必須要先拿到2. 寫入圖片"""with open('../PyPractice/images/python-logo.png', 'rb') as f: img = f.read() print(img)# 將讀取到的內容寫入到當前入件中with open('../PyPractice/images/02.png', 'wb') as f: f.write(img)輸出結果(內容太長,不顯示)

先導入模塊再進行本節其他操作
xxxxxxxxxximport os
xxxxxxxxxxos.rename('test01.txt', 'text.txt')
xxxxxxxxxxos.remove('../PyPractice/images/02.png')
xxxxxxxxxx# mrdir = make directoryos.mkdir('text')
xxxxxxxxxxos.rmdir('text')
xxxxxxxxxxprint(os.getcwd())輸出結果(根據目錄位置變化):
xxxxxxxxxx/Users/YourName/Documents/Coding/PyCharm/PyPractice
xxxxxxxxxxprint(os.listdir()) # 不寫東西,就獲取當前目錄列表print(os.listdir("../")) # 獲取上一級目錄列表輸出結果:
xxxxxxxxxx['py18.py', 'py08.py', 'py28.py', '.DS_Store', 'py29.py', 'py19.py', 'py09.py', 'pack_01', 'images', 'py26.py', 'py12.py', 'py02.py', 'py36.py', 'py16.py', 'py22.py', 'py32.py', 'py06.py', 'py17.py', 'py23.py', 'py33.py', 'py07.py', 'py27.py', 'py13.py', '__pycache__', 'py03.py', 'py37.py', 'py14.py', 'py20.py', 'py30.py', 'py04.py', 'py24.py', 'py10.py', 'pytest.py', 'py34.py', 'py25.py', 'py11.py', '.venv', 'py01.py', 'py35.py', 'py15.py', 'py21.py', 'text.txt', 'py31.py', 'py05.py', 'test.txt', 'pytest2.py', 'pytest3.py', '.idea']['.DS_Store', 'DailyUse', 'PyPractice']| 目的地 | 超連結 |
|---|---|
| 首頁 | 返回主頁 |
| Python學習 | Python學習 |
| 上一篇 | 16 - 單例模式&魔法方法 |
| 下一篇 | 18 - 迭代器&生成器 |