Ric*_*dle 3042
os.remove() 删除文件.
os.rmdir() 删除一个空目录.
shutil.rmtree() 删除目录及其所有内容.
Path 删除文件或符号链接.
pathlib 删除空目录.
ana*_*thi 227
import os
os.remove("/tmp/<file_name>.txt")
Run Code Online (Sandbox Code Playgroud)
要么
import os
os.unlink("/tmp/<file_name>.txt")
Run Code Online (Sandbox Code Playgroud)
os.path.isfile("/path/to/file")exception handling.实例为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)
Run Code Online (Sandbox Code Playgroud)
#!/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))
Run Code Online (Sandbox Code Playgroud)
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
shutil.rmtree()
Run Code Online (Sandbox Code Playgroud)
示例 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))
Run Code Online (Sandbox Code Playgroud)
Mih*_*eac 73
使用
shutil.rmtree(path[, ignore_errors[, onerror]])
Run Code Online (Sandbox Code Playgroud)
(参见关于shutil的完整文档)和/或
os.remove
Run Code Online (Sandbox Code Playgroud)
和
os.rmdir
Run Code Online (Sandbox Code Playgroud)
(关于操作系统的完整文档.)
dat*_*ght 52
在 Python 中删除文件的方法有多种,但最好的方法如下:
\nimport os\nos.remove("test_file.txt")\nprint("File removed successfully")\nRun Code Online (Sandbox Code Playgroud)\nimport os\n#checking if file exist or not\nif(os.path.isfile("test.txt")):\n #os.remove() function to remove the file\n os.remove("test.txt")\n #Printing the confirmation message of deletion\n print("File Deleted successfully")\nelse:\nprint("File does not exist")\n#Showing the message instead of throwig an error\nRun Code Online (Sandbox Code Playgroud)\nimport os \nfrom os import listdir\nmy_path = 'C:\\\\Python Pool\\\\Test'\nfor file_name in listdir(my_path):\n if file_name.endswith('.txt'):\n os.remove(my_path + file_name)\nRun Code Online (Sandbox Code Playgroud)\n要删除特定目录中的所有文件,只需使用 * 符号作为模式字符串即可。\n#导入 os 和 glob 模块\nimport os, glob\n#Loop 通过文件夹投影所有文件并通过以下方式删除它们一个\n对于 glob.glob("pythonpool/*") 中的文件:\nos.remove(file)\nprint("已删除 " + str(file))
\nos.unlink() 是 os.remove() 的别名或另一个名称。在 Unix 操作系统中,删除也称为 unlink。\n注意:所有功能和语法与 os.unlink() 和 os.remove() 相同。两者都是用于删除Python文件路径。\n两者都是Python\xe2\x80\x99s标准库中os模块中执行删除功能的方法。
\nimport shutil \nimport os \n# location \nlocation = "E:/Projects/PythonPool/"\n# directory \ndir = "Test"\n# path \npath = os.path.join(location, dir) \n# removing directory \nshutil.rmtree(path) \nRun Code Online (Sandbox Code Playgroud)\nimport shutil \nimport os \nlocation = "E:/Projects/PythonPool/"\ndir = "Test" \npath = os.path.join(location, dir) \nshutil.rmtree(path) \nRun Code Online (Sandbox Code Playgroud)\nPathlib 模块提供了与文件交互的不同方式。Rmdir 是路径函数之一,允许您删除空文件夹。首先,您需要选择目录的 Path(),然后调用 rmdir() 方法将检查文件夹大小。如果\xe2\x80\x99为空,则\xe2\x80\x99将删除它。
\n这是删除空文件夹的好方法,无需担心丢失实际数据。
\nfrom pathlib import Path\nq = Path('foldername')\nq.rmdir()\nRun Code Online (Sandbox Code Playgroud)\n
fly*_*cee 31
为你们创造一个功能.
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
Run Code Online (Sandbox Code Playgroud)
MSe*_*ert 28
您可以使用内置的pathlib模块(需要Python 3.4+,但也有旧版本的反向移植PyPI上:pathlib,pathlib2).
要删除文件,有以下unlink方法:
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
Run Code Online (Sandbox Code Playgroud)
或者rmdir删除空文件夹的方法:
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
Run Code Online (Sandbox Code Playgroud)
Aar*_*all 18
如何在Python中删除文件或文件夹?
对于Python 3,要单独删除文件和目录,请分别使用unlink和对象方法:rmdir Path
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以将相对路径与Path对象一起使用,并且可以使用以下方法检查当前的工作目录Path.cwd.
要删除Python 2中的单个文件和目录,请参阅下面标记的部分.
要删除包含内容的目录,请使用shutil.rmtree,并注意这在Python 2和3中可用:
from shutil import rmtree
rmtree(dir_path)
Run Code Online (Sandbox Code Playgroud)
Python 3.4中的新功能是Path对象.
让我们用一个来创建一个目录和文件来演示用法.请注意,我们使用它/来连接路径的各个部分,这可以解决操作系统之间的问题以及在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()
Run Code Online (Sandbox Code Playgroud)
现在:
>>> file_path.is_file()
True
Run Code Online (Sandbox Code Playgroud)
现在让我们删除它们.首先是文件:
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
Run Code Online (Sandbox Code Playgroud)
我们可以使用globbing删除多个文件 - 首先让我们为此创建一些文件:
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
Run Code Online (Sandbox Code Playgroud)
然后迭代遍历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
Run Code Online (Sandbox Code Playgroud)
现在,演示删除目录:
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
Run Code Online (Sandbox Code Playgroud)
如果我们要删除目录及其中的所有内容,该怎么办?对于这个用例,请使用shutil.rmtree
让我们重新创建我们的目录和文件:
file_path.parent.mkdir()
file_path.touch()
Run Code Online (Sandbox Code Playgroud)
并注意rmdir失败,除非它是空的,这就是rmtree如此方便的原因:
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/excelsiora/directory'
Run Code Online (Sandbox Code Playgroud)
现在,导入rmtree并将目录传递给funtion:
from shutil import rmtree
rmtree(directory_path) # remove everything
Run Code Online (Sandbox Code Playgroud)
我们可以看到整个事情已被删除:
>>> directory_path.exists()
False
Run Code Online (Sandbox Code Playgroud)
如果你在Python 2中,有一个叫pathlib2的pathlib模块的反向移植,可以PIP安装:
$ pip install pathlib2
Run Code Online (Sandbox Code Playgroud)
然后你可以将库别名为 pathlib
import pathlib2 as pathlib
Run Code Online (Sandbox Code Playgroud)
或者直接导入Path对象(如此处所示):
from pathlib2 import Path
Run Code Online (Sandbox Code Playgroud)
如果这太多了,你可以用或删除文件os.removeos.unlink
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
Run Code Online (Sandbox Code Playgroud)
要么
unlink(join(expanduser('~'), 'directory/file'))
Run Code Online (Sandbox Code Playgroud)
你可以删除目录os.rmdir:
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
Run Code Online (Sandbox Code Playgroud)
请注意,还有一个os.removedirs- 它只是递归地删除空目录,但它可能适合您的用例.
小智 11
这是我删除目录的功能。“路径”需要完整路径名。
import os
def rm_dir(path):
cwd = os.getcwd()
if not os.path.exists(os.path.join(cwd, path)):
return False
os.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))
Run Code Online (Sandbox Code Playgroud)
Shutil.rmtree 是异步函数,所以如果你想检查它什么时候完成,你可以使用 while...loop
import os
import shutil
shutil.rmtree(path)
while os.path.exists(path):
pass
print('done')
Run Code Online (Sandbox Code Playgroud)
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
Run Code Online (Sandbox Code Playgroud)
os.unlink(path, *, dir_fd=None)
Run Code Online (Sandbox Code Playgroud)
或者
os.remove(path, *, dir_fd=None)
Run Code Online (Sandbox Code Playgroud)
这两个函数在语义上是相同的。此函数移除(删除)文件路径。如果路径不是文件而是目录,则会引发异常。
shutil.rmtree(path, ignore_errors=False, onerror=None)
Run Code Online (Sandbox Code Playgroud)
或者
os.rmdir(path, *, dir_fd=None)
Run Code Online (Sandbox Code Playgroud)
为了删除整个目录树,shutil.rmtree()可以使用。os.rmdir仅当目录为空且存在时才有效。
os.removedirs(name)
Run Code Online (Sandbox Code Playgroud)
它使用 self 删除每个空的父目录,直到父目录有一些内容
前任。os.removedirs('abc/xyz/pqr') 将按顺序删除目录 'abc/xyz/pqr', 'abc/xyz' 和 'abc' 如果它们是空的。
有关更多信息,请查看官方文档:os.unlink, os.remove, os.rmdir, shutil.rmtree,os.removedirs