如何在 Python 中删除文件或文件夹?
問:
如何刪除文件或文件夾?
答1:
huntsbot.com匯聚了國內(nèi)外優(yōu)秀的初創(chuàng)產(chǎn)品創(chuàng)意,可按收入、分類等篩選,希望這些產(chǎn)品與實踐經(jīng)驗?zāi)芙o您帶來靈感。
os.remove() 刪除一個文件。
os.rmdir() 刪除一個空目錄。
shutil.rmtree() 刪除目錄及其所有內(nèi)容。
Python 3.4+ pathlib 模塊中的 Path 對象還公開了這些實例方法:
pathlib.Path.unlink() 刪除文件或符號鏈接。
pathlib.Path.rmdir() 刪除一個空目錄。
即使目標目錄不為空,Windows 上的 os.rmdir() 也會刪除目錄符號鏈接
如果文件不存在,os.remove() 會引發(fā)異常,因此可能需要先檢查 os.path.isfile(),或?qū)?try 包裝起來。
只是為了完成...如果文件不存在,則 os.remove() 引發(fā)的異常是 FileNotFoundError。
os.remove() 是否需要多個參數(shù)來刪除多個文件,還是每次都為每個文件調(diào)用它?
@Jér?me 我認為 3.8 中的 missing_ok=True, added 解決了這個問題!
答2:
huntsbot.com全球7大洲遠程工作機會,探索不一樣的工作方式
刪除文件的 Python 語法
import os os.remove("/tmp/.txt")或者
import os os.unlink("/tmp/.txt")或者
pathlib Python 庫版本 >= 3.4
file_to_rem = pathlib.Path("/tmp/.txt") file_to_rem.unlink()Path.unlink(missing_ok=False)
用于刪除文件或符號鏈接的取消鏈接方法。
如果 missing_ok 為 false(默認值),則在路徑不存在時引發(fā) FileNotFoundError。如果 missing_ok 為真,FileNotFoundError 異常將被忽略(與 POSIX rm -f 命令的行為相同)。在 3.8 版更改: 添加了 missing_ok 參數(shù)。
最佳實踐
首先,檢查文件或文件夾是否存在,然后只刪除該文件。這可以通過兩種方式實現(xiàn): os.path.isfile(“/path/to/file”) b.使用異常處理。
os.path.isfile 的示例
#!/usr/bin/python import os myfile="/tmp/foo.txt"## If file exists, delete it ## if os.path.isfile(myfile):os.remove(myfile) else: ## Show an error ##print("Error: %s file not found" % myfile)異常處理
#!/usr/bin/python import os## Get input ## myfile= raw_input("Enter file name to delete: ")## Try to delete the file ## try:os.remove(myfile) except OSError as e: ## if failed, report it back to the user ##print ("Error: %s - %s." % (e.filename, e.strerror))相應(yīng)的輸出
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory.Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted.Enter file name to delete : foo.txt刪除文件夾的 Python 語法
shutil.rmtree()shutil.rmtree() 的示例
#!/usr/bin/python import os import sys import shutil# Get directory name mydir= raw_input("Enter directory name: ")## Try to remove tree; if failed show an error using try...except on screen try:shutil.rmtree(mydir) except OSError as e:print ("Error: %s - %s." % (e.filename, e.strerror))建議進行異常處理而不是檢查,因為文件可以在兩行之間刪除或更改(TOCTOU:en.wikipedia.org/wiki/Time_of_check_to_time_of_use)請參閱 Python 常見問題解答 docs.python.org/3/glossary.html#term-eafp
在 Python 中,EAFP 也優(yōu)于 LBYL。
在最后一個示例中捕獲異常有什么意義?
答3:
huntsbot.com聚合了超過10+全球外包任務(wù)平臺的外包需求,尋找外包任務(wù)與機會變的簡單與高效。
利用
shutil.rmtree(path[, ignore_errors[, onerror]])(請參閱 shutil 上的完整文檔)和/或
os.remove和
os.rmdir(關(guān)于 os 的完整文檔。)
請將 pathlib 接口(自 Python 3.4 以來的新接口)添加到您的列表中。
答4:
huntsbot.com匯聚了國內(nèi)外優(yōu)秀的初創(chuàng)產(chǎn)品創(chuàng)意,可按收入、分類等篩選,希望這些產(chǎn)品與實踐經(jīng)驗?zāi)芙o您帶來靈感。
這是一個同時使用 os.remove 和 shutil.rmtree 的強大函數(shù):
def remove(path):""" param could either be relative or absolute. """if os.path.isfile(path) or os.path.islink(path):os.remove(path) # remove the fileelif os.path.isdir(path):shutil.rmtree(path) # remove dir and all containselse:raise ValueError("file {} is not a file or dir.".format(path))即 8 行代碼來模擬 ISO C remove(path); 調(diào)用。
@Kaz 同意煩人,但刪除處理樹木嗎? :-)
os.path.islink(file_path): 一個錯誤,應(yīng)該是 os.path.islink(path):
答5:
huntsbot.com – 程序員副業(yè)首選,一站式外包任務(wù)、遠程工作、創(chuàng)意產(chǎn)品分享訂閱平臺。
您可以使用內(nèi)置的 pathlib 模塊(需要 Python 3.4+,但 PyPI 上有舊版本的向后移植:pathlib、pathlib2)。
要刪除文件,有 unlink 方法:
import pathlib path = pathlib.Path(name_of_file) path.unlink()或刪除 empty 文件夾的 rmdir 方法:
import pathlib path = pathlib.Path(name_of_folder) path.rmdir()HuntsBot周刊–不定時分享成功產(chǎn)品案例,學(xué)習(xí)他們?nèi)绾纬晒⒆约旱母睒I(yè)–huntsbot.com
但是,非空目錄呢?
@Pranasas 不幸的是,pathlib 中似乎沒有任何東西(本機)可以處理刪除非空目錄。但是您可以使用 shutil.rmtree。其他幾個答案中都提到了它,所以我沒有包括它。
答6:
huntsbot.com精選全球7大洲遠程工作機會,涵蓋各領(lǐng)域,幫助想要遠程工作的數(shù)字游民們能更精準、更高效的找到對方。
如何在 Python 中刪除文件或文件夾?
對于 Python 3,要單獨刪除文件和目錄,請分別使用 unlink 和 rmdir Path 對象方法:
from pathlib import Path dir_path = Path.home() / 'directory' file_path = dir_path / 'file'file_path.unlink() # remove filedir_path.rmdir() # remove directory請注意,您還可以對 Path 對象使用相對路徑,并且可以使用 Path.cwd 檢查您當(dāng)前的工作目錄。
要在 Python 2 中刪除單個文件和目錄,請參閱下面標記的部分。
要刪除包含內(nèi)容的目錄,請使用 shutil.rmtree,并注意這在 Python 2 和 3 中可用:
from shutil import rmtreermtree(dir_path)示范
Python 3.4 中的新功能是 Path 對象。
讓我們用一個來創(chuàng)建目錄和文件來演示用法。請注意,我們使用 / 連接路徑的各個部分,這可以解決操作系統(tǒng)之間的問題以及在 Windows 上使用反斜杠的問題(您需要將反斜杠加倍,如 \ 或使用原始字符串,如r"foo\bar"):
from pathlib import Path# .home() is new in 3.5, otherwise use os.path.expanduser('~') directory_path = Path.home() / 'directory' directory_path.mkdir()file_path = directory_path / 'file' file_path.touch()現(xiàn)在:
>>> file_path.is_file() True現(xiàn)在讓我們刪除它們。首先是文件:
>>> file_path.unlink() # remove file >>> file_path.is_file() False >>> file_path.exists() False我們可以使用 globbing 刪除多個文件 - 首先讓我們?yōu)榇藙?chuàng)建一些文件:
>>> (directory_path / 'foo.my').touch() >>> (directory_path / 'bar.my').touch()然后只需遍歷 glob 模式:
>>> for each_file_path in directory_path.glob('*.my'): ... print(f'removing {each_file_path}') ... each_file_path.unlink() ... removing ~/directory/foo.my removing ~/directory/bar.my現(xiàn)在,演示刪除目錄:
>>> directory_path.rmdir() # remove directory >>> directory_path.is_dir() False >>> directory_path.exists() False如果我們想刪除一個目錄及其中的所有內(nèi)容怎么辦?對于此用例,請使用 shutil.rmtree
讓我們重新創(chuàng)建我們的目錄和文件:
file_path.parent.mkdir() file_path.touch()并注意 rmdir 失敗,除非它為空,這就是 rmtree 如此方便的原因:
>>> directory_path.rmdir() Traceback (most recent call last):File "", line 1, in File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdirself._accessor.rmdir(self)File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrappedreturn strfunc(str(pathobj), *args) OSError: [Errno 39] Directory not empty: '/home/username/directory'現(xiàn)在,導(dǎo)入 rmtree 并將目錄傳遞給函數(shù):
from shutil import rmtree rmtree(directory_path) # remove everything我們可以看到整個東西都被刪除了:
>>> directory_path.exists() False蟒蛇2
如果您使用的是 Python 2,則有一個 backport of the pathlib module called pathlib2,可以使用 pip 安裝:
$ pip install pathlib2然后您可以將該庫別名為 pathlib
import pathlib2 as pathlib或者直接導(dǎo)入 Path 對象(如此處所示):
from pathlib2 import Path如果太多,您可以使用 os.remove or os.unlink 刪除文件
from os import unlink, remove from os.path import join, expanduserremove(join(expanduser('~'), 'directory/file'))或者
unlink(join(expanduser('~'), 'directory/file'))您可以使用 os.rmdir 刪除目錄:
from os import rmdirrmdir(join(expanduser('~'), 'directory'))請注意,還有一個 os.removedirs - 它只會遞歸刪除空目錄,但它可能適合您的用例。
rmtree(directory_path) 適用于 python 3.6.6 但不適用于 python 3.5.2 - 你需要 rmtree(str(directory_path))) 那里。
答7:
打造屬于自己的副業(yè),開啟自由職業(yè)之旅,從huntsbot.com開始!
在 Python 中刪除文件或文件夾
在 Python 中有多種刪除文件的方法,但最好的方法如下:
os.remove() 刪除一個文件。 os.unlink() 刪除一個文件。它是 remove() 方法的 Unix 名稱。 shutil.rmtree() 刪除目錄及其所有內(nèi)容。 pathlib.Path.unlink() 刪除單個文件 pathlib 模塊在 Python 3.4 及更高版本中可用。
os.remove()
示例 1:使用 os.remove() 方法刪除文件的基本示例。
import os os.remove("test_file.txt") print("File removed successfully")示例 2:使用 os.path.isfile 檢查文件是否存在并使用 os.remove 將其刪除
import os #checking if file exist or not if(os.path.isfile("test.txt")):#os.remove() function to remove the fileos.remove("test.txt")#Printing the confirmation message of deletionprint("File Deleted successfully") else: print("File does not exist") #Showing the message instead of throwig an error示例 3:刪除具有特定擴展名的所有文件的 Python 程序
import os from os import listdir my_path = 'C:\Python Pool\Test\' for file_name in listdir(my_path):if file_name.endswith('.txt'):os.remove(my_path + file_name)示例 4:刪除文件夾內(nèi)所有文件的 Python 程序
要刪除特定目錄中的所有文件,您只需使用 * 符號作為模式字符串。 #導(dǎo)入os和glob模塊 import os, glob #循環(huán)通過文件夾項目所有文件,并一一刪除 for file in glob.glob(“pythonpool/*”): os.remove(file) print("Deleted " +字符串(文件))
os.unlink()
os.unlink() 是 os.remove() 的別名或另一個名稱。在 Unix 操作系統(tǒng)中,刪除也稱為取消鏈接。注意:所有功能和語法與 os.unlink() 和 os.remove() 相同。它們都用于刪除 Python 文件路徑。兩者都是 Python 標準庫中 os 模塊中執(zhí)行刪除功能的方法。
shutil.rmtree()
示例 1:使用 shutil.rmtree() 刪除文件的 Python 程序
import shutil import os # location location = "E:/Projects/PythonPool/" # directory dir = "Test" # path path = os.path.join(location, dir) # removing directory shutil.rmtree(path)示例 2:使用 shutil.rmtree() 刪除文件的 Python 程序
import shutil import os location = "E:/Projects/PythonPool/" dir = "Test" path = os.path.join(location, dir) shutil.rmtree(path)pathlib.Path.rmdir() 刪除空目錄
Pathlib 模塊提供了與文件交互的不同方式。 Rmdir 是允許您刪除空文件夾的路徑功能之一。首先,您需要為目錄選擇 Path(),然后調(diào)用 rmdir() 方法將檢查文件夾大小。如果它是空的,它將刪除它。
這是刪除空文件夾而不用擔(dān)心丟失實際數(shù)據(jù)的好方法。
from pathlib import Path q = Path('foldername') q.rmdir()答8:
一個優(yōu)秀的自由職業(yè)者,應(yīng)該有對需求敏感和精準需求捕獲的能力,而huntsbot.com提供了這個機會
shutil.rmtree 是異步函數(shù),所以如果你想檢查它什么時候完成,你可以使用 while…loop
import os import shutilshutil.rmtree(path)while os.path.exists(path):passprint('done')shutil.rmtree 不應(yīng)該是異步的。但是,它可能出現(xiàn)在帶有病毒掃描程序干擾的 Windows 上。
@mhsmith 病毒掃描程序?這是瘋狂的猜測,還是你真的知道它們會造成這種影響?如果是這樣,那到底是如何工作的?
答9:
huntsbot.com提供全網(wǎng)獨家一站式外包任務(wù)、遠程工作、創(chuàng)意產(chǎn)品分享與訂閱服務(wù)!
import osfolder = '/Path/to/yourDir/' fileList = os.listdir(folder)for f in fileList:filePath = folder + '/'+fif os.path.isfile(filePath):os.remove(filePath)elif os.path.isdir(filePath):newFileList = os.listdir(filePath)for f1 in newFileList:insideFilePath = filePath + '/' + f1if os.path.isfile(insideFilePath):os.remove(insideFilePath)這將僅刪除文件夾和子文件夾中的文件,保持文件夾結(jié)構(gòu)不變..
答10:
huntsbot.com全球7大洲遠程工作機會,探索不一樣的工作方式
對于刪除文件:
os.unlink(path, *, dir_fd=None)或者
os.remove(path, *, dir_fd=None)這兩個功能在語義上是相同的。此函數(shù)刪除(刪除)文件路徑。如果 path 不是文件并且是目錄,則會引發(fā)異常。
對于刪除文件夾:
shutil.rmtree(path, ignore_errors=False, onerror=None)或者
os.rmdir(path, *, dir_fd=None)為了刪除整個目錄樹,可以使用 shutil.rmtree()。 os.rmdir 僅在目錄為空且存在時有效。
對于向父級遞歸刪除文件夾:
os.removedirs(name)它使用 self 刪除每個空的父目錄,直到具有某些內(nèi)容的父目錄
前任。 os.removedirs(‘a(chǎn)bc/xyz/pqr’) 將按順序刪除目錄 ‘a(chǎn)bc/xyz/pqr’, ‘a(chǎn)bc/xyz’ 和 ‘a(chǎn)bc’ 如果它們是空的。
有關(guān)更多信息,請查看官方文檔:os.unlink、os.remove、os.rmdir、shutil.rmtree、os.removedirs
答11:
保持自己快人一步,享受全網(wǎng)獨家提供的一站式外包任務(wù)、遠程工作、創(chuàng)意產(chǎn)品訂閱服務(wù)–huntsbot.com
這是我刪除目錄的功能。 “路徑”需要完整的路徑名。
import osdef rm_dir(path):cwd = os.getcwd()if not os.path.exists(os.path.join(cwd, path)):return Falseos.chdir(os.path.join(cwd, path))for file in os.listdir():print("file = " + file)os.remove(file)print(cwd)os.chdir(cwd)os.rmdir(os.path.join(cwd, path))原文鏈接:https://www.huntsbot.com/qa/Pd5b/how-do-i-delete-a-file-or-folder-in-python?lang=zh_CN&from=csdn
huntsbot.com精選全球7大洲遠程工作機會,涵蓋各領(lǐng)域,幫助想要遠程工作的數(shù)字游民們能更精準、更高效的找到對方。
總結(jié)
以上是生活随笔為你收集整理的如何在 Python 中删除文件或文件夹?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017-2018-2 20165237
- 下一篇: 微信小程序实现摇筛子效果