P3 建立臨時檔案及資料夾

2021-10-06 03:16:10 字數 1315 閱讀 8451

p3.建立臨時檔案及資料夾.md

#寫入和讀取檔案

#讀取檔案

open(), readlines(),close()

例:f = open('file.txt','r',encoding='utf-8')

text = f.readlines()

print(text)

f.close()

例2:(推薦,不用寫colse())

with open('file.txt','r',encoding='utf-8') as f:

text =f.readlines()

print(text)

#寫入檔案

open(), write()

例:with open('file.txt','w',endcoding='utf-8') as f:

text = '第一行內容\n第二行內容\n'

f.write(text)

f.write('第三行內容 ')

#'w'表示寫入檔案

#若無該檔案,則建立乙個

#如有該檔案,裡面的內容會被清空

#'a'表示寫入檔案

#若無該檔案,則建立乙個

#如有該檔案,會在檔案的內容後面繼續寫入

#建立臨時檔案及資料夾

#建立臨時檔案儲存資料

temporaryfile()

例:from tempfile import temporaryfile

f = temporaryfile('w+')

f.write('hello')

f.seek(0)

data = f.readlines()

print(data)

f.close()

#'w='表示寫入及讀取檔案

#.seek(0)表示回到檔案頭位置

#程式執行完後會自動刪掉臨時檔案

#例2:用with……as……

with temporaryfile('w+') as f:

f.write('hello')

f.seek(0)

data = f.readlines()

print(data)

#建立臨時資料夾

temporarydirectory()

例:from tempfile import temporarydirectory

with temporarydirectory() as tmp_folder:

print(f'臨時資料夾已建立:')

#程式執行結束後自動刪掉該資料夾

建立臨時檔案及資料夾

建立臨時資料夾 在臨時檔案進行資料讀寫,需要了解python讀寫檔案以及 tempfile 模組 1 臨時檔案的讀取以游標為準from tempfile import temporaryfile f temporaryfile w w 表示寫入及讀取檔案 f.write hello world da...

python 建立臨時檔案和資料夾

需要在程式執行時建立乙個臨時檔案或目錄,並希望使用完之後可以自動銷毀掉。tempfile 模組中有很多的函式可以完成這任務。為了建立乙個匿名的臨時檔案,可以使用tempfile.temporaryfile from tempfile import temporaryfile with tempora...

python中臨時檔案及資料夾使用

三 臨時檔案 這裡介紹python中臨時檔案及資料夾使用。使用的是tempfile包 安裝 pip install tempfile 參考位址是 2.1 獲取臨時資料夾 獲取臨時資料夾 tmpdir tempfile.gettempdir print tmpdir tmp2.2 生成臨時資料夾 方式...