Learn Python the Hard Way 15 Reading Files
Published in
4 min readSep 11, 2019
用 Python 來讀取檔案
這次來練習怎麼讀取檔案,我們先來建立一個 txt 檔,檔案名稱就叫 ex15_sample.txt 吧,內容如下,亂打也沒差。
This is stuff I typed in to a file.
It is really cool stuff.
Lots and lots of fun to have in here.
接著今天的 code:
from sys import argvscript, filename = argvtxt = open(filename)print(f"Here's your file {filename}:")
print(txt.read())print("Type the filename again:")
file_again = input("> ")txt_again = open(file_again)print(txt_again.read())
在這邊我們用了 open() 來打開我們的檔案,用 read () 來讀取裡面的內容。
我們在 terminal 輸入:
python ex15.py ex15_sample.txt
會得到輸出 (我在文檔多加了兩行空行):
Here's your file ex15_sample.txt:
This is stuff I typed in to a file.
It is really cool stuff.
Lots and lots of fun to have in here.Type the filename again:
> ex15_sample.txt
This is stuff I typed in to a file.
It is really cool stuff.
Lots and lots of fun to have in here.
利用 comment 來解釋 code:
#import argv
from sys import argv
# 將 argv 分成 script, filename 兩個變數
script, filename = argv# 使用 open() 來建立 file object
txt = open(filename)# 使用 read() 讀取裡面的內容
print(f"Here's your file {filename}:")
print(txt.read()) print("Type the filename again:")
file_again = input("> ")txt_again = open(file_again)print(txt_again.read())
另外,用 open() 開啟文件,也有 close() 來關閉文件,當我們沒要使用該文件時,要養成一個好習慣就是關閉它,以免不小心讀取到又修改裡面的內容,close () 可以這樣用:
txt = open(filename)print(f"Here's your file {filename}:")
print(txt.read())
txt.close()
這系列文章的練習,都是來自於 Learn Python the Hard Way 這本書中,內容只針對練習做紀錄和自己的心得分享,為保護著作權故沒有透露太多內容,能力可及的話還是鼓勵大家買一本來自行練習,有問題都可以在下方進行討論。