7.2. 存取文字檔


當程式產生結果之後,為了要保持這些得來不易的結果,想要將這些結果輸出到檔案中,其中最直覺地的方式就是將結果存入文字檔中,即「*.txt」純文字檔。在讀取或寫入一個檔案之前,例如:文字檔,需要先將檔案開啟才能對其讀取內容或寫入資料。

使用 open() 開啟檔案

使用 open() 開啟一個檔案的語法如下:

檔案物件 = open(檔案路徑, 開啟模式)

「開啟模式」是一個字串,可以來指定檔案類型及要做什麼樣的操作,此字串可以有一到二個字元。開啟開模式的第一個字元表示操作的類型:

  • r : 表示取讀。
  • w : 表示寫入,如果檔案路徑指定的檔案不存在,則會建立一個檔案。若存在該檔案時,則它會被寫入(或複蓋)。
  • x : 表示寫入,但只有在檔案還不存在的時候。
  • a : 表示附加,如果檔案存在時,要寫入的資料會附加在檔案的最後方。

開啟模式的第二個字元表示檔案的類型:

  • t : 表示文字檔案,若沒有指定第二個字元,則檔案類型也是文字。
  • b : 表示二進位檔案。

此外,若使用「r+」開啟模式,則表示同時讀取及寫入檔案。

使用 with 自動關閉檔案

使用 open() 存取檔案的一個良好習慣是,有開啟檔案就要有關閉檔案。進一步,如果使用 with 關鍵字時,則所開啟的檔案會在讀取或寫入的動完成之後自動關閉檔案。透過 with 來開啟一個檔案的語法如下:

with open(檔案路徑, 開啟模式) as 檔案物件

讀取文字檔

下列為使用 open() 讀取一個文字檔的範例:

# 開起檔案
f = open('The_Zen_of_Python.txt', 'r')

# 讀取檔案內容
for line in f:
    print(line.strip())

# 關閉檔案
f.close()


# 執行結果
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one -- and preferably only one -- obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

下列為使用 with 讀取一個文字檔的範例:

# 開啟檔案
with open('The_Zen_of_Python.txt', 'r') as f:
    # 讀取檔案內容
    for line in f:
        print(line.strip())


# 執行結果
Beautiful is better than ugly.
...

寫入文字檔

下列為使用 with 寫入一個文字檔的範例:

# 定義變數
zen_of_python = """\
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one -- and preferably only one -- obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!\
"""

# 開啟檔案
with open('output.txt', 'w') as f:
    f.write(zen_of_python)


# 執行結果
# output.txt
Beautiful is better than ugly.
...

參考資料

  • Zen of Pyton
  • Python自動化的樂趣, 第八章, Al Sweigart 著、H&C 譯, 碁峰
  • Python編程入門第3版(簡), 第八章, Toby Donaldson著, 人民郵電出版社
  • 精通Python, 第十章, Bill Lubanovic著, 賴屹民譯, 歐萊禮

results matching ""

    No results matching ""