[英]Deleting all files in a folder in Python
我正在嘗試使用Python創建一個程序,該程序將刪除%temp%
路徑中的所有文件,也稱為C:\\Users\\User\\AppData\\Local\\Temp
。
我怎樣才能做到這一點? 我正在使用Python 3.4。
通常,您可以使用shutil.rmtree()
刪除文件夾中的所有文件/目錄:
#!/usr/bin/env python
import shutil
import tempfile
dirpath = tempfile.mkdtemp()
try:
# use the temporary directory here
...
finally:
shutil.rmtree(dirpath) # clean up
如果需要的話,上面的內容可以寫得更簡單(從頭開始創建一個臨時目錄):
#!/usr/bin/env python3
import tempfile
with tempfile.TemporaryDirectory() as dir:
print(dir.name) # use the temporary directory here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.