文、意如
讀完這篇文章你可以學到:
1. 開啟檔案寫入資料
2. 使用with開啟檔案、更新資料、寫入多行內容
3. 在原本的資料後再添加資料
4. 讀取檔案內容:只讀取幾個字元、只讀第一行、把資料轉成陣列後讀出
5. 使用For迴圈讀取資料
6. For迴圈的end="執行後要出現的文字也可以是空白"
7. 移除檔案、檔案如存在時就刪除,如果不存在就印出提示文字檔案不存在
8. 移除資料夾、資料夾如存在時就刪除,如果不存在就印出提示文字資料夾不存在
首先認識幾個參數
w:新增檔案或寫入檔案(如果無檔案會自動新增,原本有資料也會被取代掉)
a:附加(在原本的資料上再添加資料)
r:讀取檔案內容
開啟檔案寫入資料
參數:w(寫入)
程式碼解析:
#將要寫入的資料bbbbb 存在變數word 中
words='bbbbb'
#打開welcome.txt , 參數為w , 如原本沒有welcome.txt 檔案時會自己新增一個
fo=open('welcome.txt','w')
#執行寫入
fo.write(words)
#關閉檔案
fo.close()
完整程式碼:
words='bbbbb'
fo=open('welcome.txt','w')
fo.write(words)
fo.close()

因為原本沒有welcome.txt
這個檔案,所以會新增welcome.txt
這個檔案,並寫入資料

使用with開啟檔案
另一種開啟檔案的方式,如使用with來開啟檔案時會自動關閉檔案
with open('welcome.txt','r') as fo:
for LL in fo:
print(LL,end="")

更新資料
如果本身有welcome.txt這個檔案時,原本的資料內容就會被取代掉,如果無檔案會自動新增,原本有資料也會被取代掉。
參數:w(寫入)
例:
words='cccc' #改內容
fo=open('welcome.txt','w')
fo.write(words)
fo.close()
再執行一次

內容被改掉了

寫入多行內容
方式1:將文字使用三個單引號包起來即可。
words='''abcplll!!
line2222222
line3333333
line4444444
'''
fo=open('welcome.txt','w')
fo.write(words)
fo.close()

方法2:用雙引號包夾起寫入的內容,如需要斷行需使用斷行符號 \n
words="abcplll!!! \n line2222222"
fo=open('welcome.txt','w')
fo.write(words)
fo.close()

在原本的資料後再添加資料
參數:a(附加)
words='qqwert'
fo=open('welcome.txt','a')
fo.write(words)
fo.close()

已經在原本的內容後多了附加的文字

讀取檔案內容
參數:r(讀取檔案內容)
fo=open('welcome.txt','r')
w=fo.read()
print(w)
fo.close()

只讀取幾個字元
fo=open('welcome.txt','r')
ss=fo.read(5)
print(ss)
fo.close()

只讀第一行
fo=open('welcome.txt','r')
w1=fo.readline()
print(w1)
fo.close()

把資料轉成陣列後讀出
fo=open('welcome.txt','r')
w1=fo.readlines()
print(w1)
print(w1[3])
fo.close()

使用For 迴圈讀取資料
fo=open('welcome.txt','r')
for LL in fo:
print(LL) #每一圈跑一行,跑到沒資料為止
fo.close()

For迴圈的end="執行後要出現的文字也可以是空白"
fo=open('welcome.txt','r')
for LL in fo:
print(LL,end="-")
fo.close()

移除檔案
import os
file_name="welcome3.txt"
os.remove(file_name)
#ps:如果本來就沒有這個檔案的話會出現錯誤

檔案如存在時就刪除,如果不存在就印出提示文字檔案不存在
import os
file_name="welcome.txt"
if (os.path.exists(file_name)):
os.remove(file_name)
print(file_name+"已刪除檔案")
else:
print(file_name+"檔案不存在")

當檔案不存在時,要出現提示文字

移除資料夾
import os
dir_name="Hello"
os.rmdir(dir_name)
#ps:如果本來就沒有這個資料夾的話會出現錯誤

資料夾如存在時就刪除,如果不存在就印出提示文字資料夾不存在
import os
dir_name="Hello"
if (os.path.exists(dir_name)):
os.rmdir(dir_name)
print(dir_name+"已刪除資料夾")
else:
print(dir_name+"資料夾不存在")

Yiru@Studio - 關於我 - 意如