iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

Python初學者的自學筆記系列 第 28

Day28初見檔案

開啟檔案:Python有內建一個基本語法,基本語法如下。
檔案物件=open(檔案路徑,mode=開啟模式)
開啟模式的樣式如下
讀取模式:r
寫入模式:W
讀寫模式r+
那要如何讀取檔案裡面的文字,接下來來介紹讀取文字的方法
檔案物件.read() 讀取全部的文字
for 變數in 檔案物件:一次讀取一行,從檔案依序讀取每一行文字到變數中
寫入文字
檔案物件.write(字串)
https://ithelp.ithome.com.tw/upload/images/20191013/20120877efKwiwQ9fd.png
如果要換行的要寫入換行符號\n
檔案物件.write(“Test\n”)

file = open ("data.txt",mode = "w")
file.write("hello\nSecond")
file.close()

結果:
https://ithelp.ithome.com.tw/upload/images/20191013/20120877Wzm9tcbqyG.png
那如果要輸入中文那要如何寫呢,那便是在open裡加encoding

file = open ("data.txt",mode = "w",encoding="utf-8")
file.write("你好\n再見")
file.close()

結果:
你好
再見

關閉檔案
基本語法

檔案物件.close()

Python本身提供了最佳實務的語法
with open(檔案路徑, mode = 開啟模式) as 檔案物件:
讀取或寫入檔案的程式
這一段程式會自動且安全的把檔案關閉,不用額外的寫close()

with open ("data.txt",mode="w",encoding="utf-8") as file:
    file.write("你好\n123")

結果:
https://ithelp.ithome.com.tw/upload/images/20191013/20120877ap2RiNl9Wq.png


上一篇
Day27物件導向
下一篇
Day29 檔案(二)
系列文
Python初學者的自學筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言