python學習筆記 寫檔案

2021-09-09 06:35:30 字數 1230 閱讀 4369

out = open(「data.txt」,「w」)

data.txt為所寫檔案的檔名,w為使用的訪問模式

使用w模式時,若是這個檔案已經存在,會清空現有的內容;若是檔案不存在,會重新建立乙個檔案。

1.將字串寫進檔案

"hello word"為寫至檔案的內容

out = open("skech.txt","w")

out.write("hello word")

out.close()

2.list寫進檔案

可利用for迴圈

manlist = ["aa","bb","cc"]

for i in manlist:

out.write(i +'\n')

strip() 方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字串行。

該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。

ss = "  eeehhhhererrrree "

print (ss)

print (ss.strip('e'))

print (ss.strip())

sss = "eeehhhhererrrree"

print (sss.strip('e'))

eeehhhhererrrree

eeehhhhererrrree

eeehhhhererrrree

hhhhererrrr

不論什麼情況finally組中的**總會執行

try:

data = open('its.txt',"w")

data.write("it's ...")

except ioerror as err:

print ('file error:' + str(err))

finally:

if 'data' in locals():

data.close()

使用with時,不需要操心關閉開啟的檔案

try:

with open('its.txt',"w") as data:

data.write("it's ...")

except ioerror as err:

print ('file error:' + str(err))

Python學習筆記 檔案寫操作

w 檔案寫操作,如果檔案存在,會把檔案的內容清空,再繼續下面的操作。檔案不存在,首先會新建乙個檔案 f open 寫笑話檔案 w f.write 第一行11111111111 n f.write 第二行22222222222 n f.write 第三行33333333333 n f.writelin...

Python學習筆記 檔案

3 檔案 目錄的常用管理操作 計算機的檔案,就是儲存在某種 長期儲存裝置 上的一段資料 在計算機中,檔案是以二進位制的方式儲存在磁碟上的 在 計算機 中要操作檔案的套路非常固定,一共包含三個步驟 1.開啟檔案 2.讀 寫檔案 3.關閉檔案 python中操作檔案有 乙個函式和三個方法 open 函式...

Python學習筆記 檔案

開啟檔案 with open mcr license.txt as file obj contents file obj.read print contents 只能開啟txt檔案,不能開啟pdf和office檔案 路徑分為相對路徑和絕對路徑 相對路徑 with open files mcr lic...