iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
自我挑戰組

從前端角度看30天學Python系列 第 21

【Day 21】檔案處理

  • 分享至 

  • xImage
  •  
  • Open
  • 開啟及閱讀檔案
    • readline()
    • readlines()
    • str.splitlines()
  • 開啟與關閉檔案的語法糖
  • 開啟及寫入/更新檔案
  • 刪除檔案

這篇文章是閱讀Asabeneh的30 Days Of Python: Day 19 - File Handling後的學習筆記與心得。

這個章節的應用跟Node.js比較有關,因為在網頁上跑的JavaScript通常是不能跟本地端的檔案互動的,要透過瀏覽器,但又只能在基於Chromium的瀏覽器使用

這邊我也是拆成兩天寫?,覺得後面的東西愈來愈複雜,跟前端的距離愈來愈遠...開始真正的學習新知了。

  • Day 21 會寫如何跟檔案互動
  • Day 22 則是處理不同附檔名檔案的例子

Open

使用內建函式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")

上一篇
【Day 20】RegEx模式
下一篇
【Day 22】檔案類型
系列文
從前端角度看30天學Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言