Python 寫檔,寫入 txt 文字檔

本篇介紹 Python 寫檔寫入 txt 文字檔的方法,Python 寫檔是檔案處理的必備技能,在 Python 程式中常需要將程式的資料或資訊輸出成 txt 文字檔,例如:log 日誌,接著就馬上開始學習用 Python 來寫檔吧!

以下 Python 寫檔的用法範例分為這幾部份,

  • Python 基本的寫檔範例
  • 寫入 list 資料到檔案
  • 用 print() 寫入檔案
  • 使用 with open() as
  • 添加模式附加資料在原本檔案的尾巴

Python 基本的寫檔範例

Python 處理檔案中寫檔案是最常見的 IO 操作,在上一篇我們已經介紹過怎麼開檔、讀檔、關檔了,這邊就直接介紹怎麼寫入 txt 檔案,

一開始開檔 open(filename, mode) 的第二個參數使用 'w' 開檔且寫入,這邊我們示範了3種方式,分別是將字串寫入txt檔案,將整數寫入txt檔案,將浮點數寫入txt檔案,

python3-txt-write.py
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

path = 'output.txt'
f = open(path, 'w')
f.write('Hello World')
f.write(123)
f.write(123.45)
f.close()

輸出:

output.txt
1
2
3
Hello World
123
123.45

寫入 list 資料到檔案

這邊 ShengYu 介紹將 list 資料一次寫入到檔案的方法,Python 的 f.writelines() 可以接受 list 作為參數,
但要注意的是直接使用 writelines() 函式並不會換行寫入,要在寫入的字串後面加 \n 才會換行,例如,

python3-txt-write2.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

path = 'output.txt'
f = open(path, 'w')
lines = ['Hello World\n', '123', '456\n', '789\n']
f.writelines(lines)
f.close()

結果輸出如下,有注意到有換行跟沒換行的差異了嗎?

output.txt
1
2
3
Hello World
123456
789

用 print() 寫入檔案

Python print() 函式預設是將資料輸出到標準螢幕輸出,不過 print() 也可以指定將資料輸出到檔案(當然也就不會輸出在螢幕輸出了),只要在 print() 增加 file 的參數就可以了,

python3-txt-write3.py
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

path = 'output.txt'
f = open(path, 'w')
print('Hello World', file=f)
print('123', file=f)
print('456', file=f)
print('789', file=f)
f.close()

使用 with open() as

使用 with 關鍵字來開檔的優點是不必在程式裡寫關檔 close(),因為 with 會在結束這個程式碼區塊時自動將它關閉,馬上來看看 Python with 寫檔的用法範例吧!

python3-txt-write4.py
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

path = 'output.txt'
with open(path, 'w') as f:
f.write('apple\n')
f.write('banana\n')
f.write('lemon\n')
f.write('tomato\n')

添加模式附加資料在原本檔案的尾巴

Python open() 使用添加模式主要是可以將寫入的資料附加在原本檔案的尾巴,要使用添加模式需要在 open(filename, mode) 的第二個參數使用 'a' 來開檔,a 是 append 的意思,Python 添加模式範例如下,

python3-txt-write5.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

path = 'output.txt'
with open(path, 'a') as f:
f.write('apple\n')
f.write('banana\n')
f.write('tomato\n')

假設一開始沒有 output.txt,執行了三次後的結果如下,每一次的資料寫入都是從檔案尾巴開始添加,

1
2
3
4
5
6
7
8
9
apple
banana
tomato
apple
banana
tomato
apple
banana
tomato

在下一篇我將會介紹 Python 結合讀檔與寫檔的檔案讀寫範例。

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 讀取 txt 文字檔
Python 讀寫檔案
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放