readline()
readlines()
str.splitlines()
這篇文章是閱讀Asabeneh的30 Days Of Python: Day 19 - File Handling後的學習筆記與心得。
這個章節的應用跟Node.js比較有關,因為在網頁上跑的JavaScript通常是不能跟本地端的檔案互動的,要透過瀏覽器,但又只能在基於Chromium的瀏覽器使用。
這邊我也是拆成兩天寫?,覺得後面的東西愈來愈複雜,跟前端的距離愈來愈遠...開始真正的學習新知了。
使用內建函式open來開啟檔案讀寫:
語法:open(file, mode="r")
mode參數可以使用的值有:
| 字元 | 意義 |
|---|---|
| r | 唯讀(預設) |
| w | 開啟檔案供寫入,會覆寫現有內容 |
| x | 建立並開啟,如果檔案已存在就會失敗 |
| a | 開啟檔案供寫入,若檔案已存在會從檔案結尾新增內容 |
| b | 二進位模式 |
| t | 文字模式(預設) |
| + | 開啟檔案供讀與寫 |
為了方便說明,我開了一個資料夾叫test_python,並在裡面創了兩個檔案main.py以及crazy_friday.txt。透過執行main.py,去開啟並閱讀crazy_friday.txt的內容:
f = open('./crazy_friday.txt')
print(f);
# <_io.TextIOWrapper name='./crazy_friday.txt' mode='r' encoding='cp950'>
這樣會拿到一個物件,但還看不到檔案內容;要再透過這個物件的read方法回傳出字串內容:
? 如果有開啟檔案,就一定要再透過close方法關閉檔案,釋放記憶體。
f = open('./crazy_friday.txt')
txt = f.read()
print(txt)
f.close()
read(size=-1)(預設)會印出檔案中全部文字內容:TGIF. Let's party all the night!
Oh no! It seems all the beer in the town has been sold out.
Sad, I guess no party today...
若給size參數值,則能限定要印出多少字:
txt = f.read(5)
print(txt) # TGIF.
readline()使用readline(size=-1)這個方法只會回傳文本中的第一行:
line = f.readline()
print(line) # TGIF. Let's party all the night!
像read一樣,可以給size參數值,指定要印到第幾個字元。
readlines()使用readlines(hint=-1)這個方法回依據文本中的斷行(\n),回傳一個 list:
lines = f.readlines()
print(lines) # ["TGIF. Let's party all the night!\n", '\n', 'Oh no! It seems all the beer in the town has been sold out.\n', '\n', 'Sad, I guess no party today...']
若給hint參數值,則會印到所有段落中所含總字元數不超出該值的段落:
lines = f.readlines(34)
print(lines) # ["TGIF. Let's party all the night!\n", '\n', 'Oh no! It seems all the beer in the town has been sold out.\n']
str.splitlines()另一個可以傳回依據段落分割的 list 的方法是接著 read 使用 splitlines:
f = open('./crazy_friday.txt')
lines = f.read().splitlines()
print(lines) # ["TGIF. Let's party all the night!", '', 'Oh no! It seems all the beer in the town has been sold out.', '', 'Sad, I guess no party today...']
f.close()
前面提到如果有開檔,就一定要關檔,Python中提供了with這個 keyword 讓程式能在該 clause 執行後自動關閉檔案:
with open('./crazy_friday.txt') as f:
line = f.readline(17)
print(line) # TGIF. Let's party
# 下面是一般的寫法
f = open('./crazy_friday.txt')
lines = f.readlines(17)
print(lines) # ["TGIF. Let's party all the night!\n"]
f.close()
在沒有關檔的情況下繼續讀的話會:
with open('./crazy_friday.txt') as f:
line = f.readline(17)
lines = f.readlines(17)
print(line) # TGIF. Let's party
print(lines) # [' all the night!\n', '\n', 'Oh no! It seems all the beer in the town has been sold out.\n']
realines變成從readline讀完的地方繼續讀。透過給 open(file, mode="r") 第二個參數做到:
mode="a":會在檔案結尾新增字串,如果檔案不存在,就會創造一個新的檔案:with open('./crazy_friday.txt', 'a') as f:
f.write('This text has to be appended at the end.')
with open('./crazy_friday.txt') as f:
txt = f.read()
print(txt)
"""
TGIF. Let's party all the night!
Oh no! It seems all the beer in the town has been sold out.
Sad, I guess no party today...This text has to be appended at the end.
"""
mode="w":會覆寫現有的檔案內容,如果檔案不存在,則會創造一個新的檔案:with open('./crazy_friday.txt', 'w') as f:
f.write('This text will be written in a newly created file')
with open('./crazy_friday.txt') as f:
txt = f.read()
print(txt) # This text will be written in a newly created file
透過 os 模組(module)可以從檔案目錄中移除檔案,如果該檔案不存在,會拋出 FileNotFoundError:
import os
os.remove('./crazy_friday.txt')
可以加上一個判斷式,避免程式中斷:
import os
if os.path.exists("./crazy_friday.txt"):
os.remove("./crazy_friday.txt")
else:
print("The file does not exist")