#!/usr/bin/python
import os
myfile = "/tmp/foo.txt"
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
else:
# If it fails, inform the user.
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 it fails, inform the user.
print("Error: %s - %s." % (e.filename, e.strerror))
相应输出
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()
Python 语法shutil.rmtree() 的示例
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir = raw_input("Enter directory name: ")
# Try to remove the tree; if it fails, throw an error using try...except.
try:
shutil.rmtree(mydir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
Unlink method used to remove the file or the symbolik link.
If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
Best practice
First, check if the file or folder exists and then delete it. You can achieve this in two ways:
os.path.isfile("/path/to/file")
Use exception handling.
EXAMPLE for 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:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)
Exception Handling
#!/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 it fails, inform the user.
print("Error: %s - %s." % (e.filename, e.strerror))
Respective output
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 syntax to delete a folder
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir = raw_input("Enter directory name: ")
# Try to remove the tree; if it fails, throw an error using try...except.
try:
shutil.rmtree(mydir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(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))
Here is a robust function that uses both os.remove and shutil.rmtree:
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(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))
import os
# check if file exist or not
if os.path.isfile("test.txt"):
# remove the file
os.remove("test.txt")
else:
# Show the message instead of throwing an error
print("File does not exist")
示例 3:删除具有特定扩展名的所有文件
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:删除文件夹内所有文件的 Python 程序
要删除特定目录内的所有文件,您只需使用 *符号作为模式字符串。
import os, glob
# Loop over all files and delete them one by one
for file in glob.glob("pythonpool/*"):
os.remove(file)
print("Deleted " + str(file))
from pathlib import Path
q = Path('foldername')
q.rmdir()
Deleting a file or folder in Python
There are multiple ways to delete a file in Python but the best ways are the following:
os.remove() removes a file.
os.unlink() removes a file. It is a Unix alias of remove().
shutil.rmtree() deletes a directory and all its contents.
pathlib.Path.unlink() deletes a single file The pathlib module is available in Python 3.4 and above.
os.remove()
Example 1: Remove a file using os.remove()
import os
os.remove("test_file.txt")
Example 2: Check if file exists using os.path.isfile() and delete it with os.remove()
import os
# check if file exist or not
if os.path.isfile("test.txt"):
# remove the file
os.remove("test.txt")
else:
# Show the message instead of throwing an error
print("File does not exist")
Example 3: Delete all files with a specific extension
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)
Example 4: Python Program to Delete All Files Inside a Folder
To delete all files inside a particular directory, you simply have to use the * symbol as the pattern string.
import os, glob
# Loop over all files and delete them one by one
for file in glob.glob("pythonpool/*"):
os.remove(file)
print("Deleted " + str(file))
os.unlink()
os.unlink() is an alias or another name of os.remove(). As in the Unix OS remove is also known as unlink.
Note: All the functionalities and syntax is the same of os.unlink() and os.remove(). Both of them are used to delete the Python file path.
Both are methods in the os module in Python’s standard libraries which performs the deletion function.
shutil.rmtree()
Example 1: Delete a file using shutil.rmtree()
import shutil
import os
location = "E:/Projects/PythonPool/"
dir = "Test"
path = os.path.join(location, dir)
# remove directory
shutil.rmtree(path)
pathlib.Path.rmdir() to remove empty directory
The Pathlib module provides different ways to interact with your files. Rmdir is one of the path functions which allows you to delete an empty folder. Firstly, you need to select the Path() for the directory, calling rmdir() method will check the folder size. If it’s empty, it’ll delete it.
This is a good way to deleting empty folders without any fear of losing actual data.
from pathlib import Path
q = Path('foldername')
q.rmdir()
我们用一个来创建一个目录和文件来演示用法。请注意,我们使用 / 来连接路径的各个部分,这可以解决操作系统之间的问题以及在 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()
Note that you can also use relative paths with Path objects, and you can check your current working directory with Path.cwd.
For removing individual files and directories in Python 2, see the section so labeled below.
To remove a directory with contents, use shutil.rmtree, and note that this is available in Python 2 and 3:
from shutil import rmtree
rmtree(dir_path)
Demonstration
New in Python 3.4 is the Path object.
Let's use one to create a directory and file to demonstrate usage. Note that we use the / to join the parts of the path, this works around issues between operating systems and issues from using backslashes on Windows (where you'd need to either double up your backslashes like \\ or use raw strings, like 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()
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)
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)
Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.
My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.
In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...
It also wraps shutil.rmtree:
gt; python -m pip install pathlib3x
gt; python
>>> import pathlib3x as pathlib
# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)
# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
删除目录中的所有文件夹
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
To remove all files in folder
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
To remove all folders in a directory
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
import os
def del_dir(rootdir):
for (dirpath, dirnames, filenames) in os.walk(rootdir):
for filename in filenames: os.remove(rootdir+'/'+filename)
for dirname in dirnames: del_dir(rootdir+'/'+dirname)
os.rmdir(rootdir)
import os
def del_dir(rootdir):
for (dirpath, dirnames, filenames) in os.walk(rootdir):
for filename in filenames: os.remove(rootdir+'/'+filename)
for dirname in dirnames: del_dir(rootdir+'/'+dirname)
os.rmdir(rootdir)
import glob
from os import path, remove, rmdir
#The directory you wish to empty...
your_dir = "/path/to/dir/with/contents"
# Use list comprehension to ensure we don't compromise on speed
[
remove(f) if path.isfile(f)
else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]
for f in glob.glob(path.join(your_dir, "*"))
]
它的工作原理是这样的:
我们首先使用 glob 来获取要清空的目录中的所有文件和目录。在本例中,“your_dir” for f in glob.glob(path.join(your_dir, "*"))
然后我们删除此“父目录”中的所有文件 remove(f) if path.isfile(f)
这行else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]是最 有趣的。
首先,因为这些将是目录,所以我们使用 glob 和 remove 组合清空它们 [remove(ff) for ff in glob.glob(path.join(f , "*"))]
There is a simple and effective way to remove all files and directories using List Comprehension.
import glob
from os import path, remove, rmdir
#The directory you wish to empty...
your_dir = "/path/to/dir/with/contents"
# Use list comprehension to ensure we don't compromise on speed
[
remove(f) if path.isfile(f)
else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]
for f in glob.glob(path.join(your_dir, "*"))
]
This is what it works:
We first use glob to get all files and directories in the directory you want to empty. In this case, "your_dir" for f in glob.glob(path.join(your_dir, "*"))
Then we remove any files within this "parent directory" remove(f) if path.isfile(f)
This line else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)] is the most interesting.
First, because these will be directories we empty them using the glob and remove combination [remove(ff) for ff in glob.glob(path.join(f, "*"))]
Now that the "child directory" is empty, we need rmdir to remove it. To do so, we use a hack; list concatenation. By adding + [rmdir(f)] we force python to evaluate rmdir(f) and thus remove the directory for us. Viola!
import os
from os import walk
path1 = './mypath1/'
[os.remove(path1+ff) for ff in next(walk(path1), (None, None, []))[2]]
如果您有各种您要删除的目录所有文件:
import os
from os import walk
path1 = "./mypath1/"
path2 = "./mypath2/"
path3 = "./mypath3/"
for p in [path1,path2,path3]:
[os.remove(p+ff) for ff in next(walk(p), (None, None, []))[2]]
import os
from os import walk
path1 = './mypath1/'
[os.remove(path1+ff) for ff in next(walk(path1), (None, None, []))[2]]
If you have various directories you want to delete all files:
import os
from os import walk
path1 = "./mypath1/"
path2 = "./mypath2/"
path3 = "./mypath3/"
for p in [path1,path2,path3]:
[os.remove(p+ff) for ff in next(walk(p), (None, None, []))[2]]
发布评论
评论(18)
使用以下方法之一:
pathlib.Path .unlink()
删除文件或符号链接。pathlib.Path.rmdir()
删除一个空目录。
shutil.rmtree()
删除目录及其所有内容。在 Python 3.3 及更低版本上,您可以使用这些方法代替
pathlib
个:os.remove()< /code>
删除一个文件。
os.unlink()
删除符号链接。os.rmdir()
删除一个空目录。Use one of these methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.On Python 3.3 and below, you can use these methods instead of the
pathlib
ones:os.remove()
removes a file.os.unlink()
removes a symbolic link.os.rmdir()
removes an empty directory.用于删除文件
或
pathlib 库的 Python 语法对于 Python 版本 >= 3.4
Path.unlink(missing_ok=False)
用于删除文件或符号链接的取消链接方法。
最佳实践
首先,检查文件或文件夹是否存在,然后将其删除。您可以通过两种方式实现此目的:
os.path.isfile("/path/to/file")
异常处理。
示例
os.path.isfile
异常处理
相应输出
用于删除文件夹的
Python 语法
shutil.rmtree()
的示例Python syntax to delete a file
or
or
pathlib Library for Python version >= 3.4
Path.unlink(missing_ok=False)
Unlink method used to remove the file or the symbolik link.
Best practice
First, check if the file or folder exists and then delete it. You can achieve this in two ways:
os.path.isfile("/path/to/file")
exception handling.
EXAMPLE for
os.path.isfile
Exception Handling
Respective output
Python syntax to delete a folder
Example for
shutil.rmtree()
使用
(请参阅 shutil 上的完整文档)和/或
和
(shutil 上的完整文档="http://docs.python.org/library/os.html#os.remove" rel="noreferrer">操作系统。)
Use
(See complete documentation on shutil) and/or
and
(Complete documentation on os.)
这是一个使用 os.remove 和 shutdownt.rmtree 的强大函数:
Here is a robust function that uses both
os.remove
andshutil.rmtree
:在 Python 中删除文件或文件夹
在 Python 中删除文件的方法有多种,但最好的方法如下:
os.remove()
删除文件。os.unlink()
删除文件。它是remove() 的Unix 别名。shutil.rmtree()
删除目录及其所有内容。pathlib.Path.unlink()
删除单个文件 pathlib 模块在 Python 3.4 及更高版本中可用。os.remove()
示例 1:使用
os.remove()
删除文件示例 2:使用
os.path.isfile()
检查文件是否存在并使用以下命令删除它os.remove()
示例 3:删除具有特定扩展名的所有文件
示例 4:删除文件夹内所有文件的 Python 程序
要删除特定目录内的所有文件,您只需使用 *符号作为模式字符串。
os.unlink()
os.unlink()
是os.remove()
的别名或其他名称。在 Unix 操作系统中,删除也称为取消链接。注意:所有功能和语法与 os.unlink() 和 os.remove() 相同。两者都是用来删除Python文件路径的。
两者都是 Python 标准库中 os 模块中执行删除功能的方法。
Shutil.rmtree()
示例 1:使用
shutil.rmtree()
删除文件pathlib.Path.rmdir() 删除空目录
Pathlib
模块提供了不同的交互方式和你的文件。 Rmdir 是路径函数之一,允许您删除空文件夹。首先,您需要选择目录的Path()
,调用rmdir()
方法将检查文件夹大小。如果为空,则会将其删除。这是删除空文件夹的好方法,无需担心丢失实际数据。
Deleting a file or folder in Python
There are multiple ways to delete a file in Python but the best ways are the following:
os.remove()
removes a file.os.unlink()
removes a file. It is a Unix alias of remove().shutil.rmtree()
deletes a directory and all its contents.pathlib.Path.unlink()
deletes a single file The pathlib module is available in Python 3.4 and above.os.remove()
Example 1: Remove a file using
os.remove()
Example 2: Check if file exists using
os.path.isfile()
and delete it withos.remove()
Example 3: Delete all files with a specific extension
Example 4: Python Program to Delete All Files Inside a Folder
To delete all files inside a particular directory, you simply have to use the * symbol as the pattern string.
os.unlink()
os.unlink()
is an alias or another name ofos.remove()
. As in the Unix OS remove is also known as unlink.Note: All the functionalities and syntax is the same of
os.unlink()
andos.remove()
. Both of them are used to delete the Python file path.Both are methods in the
os
module in Python’s standard libraries which performs the deletion function.shutil.rmtree()
Example 1: Delete a file using
shutil.rmtree()
pathlib.Path.rmdir() to remove empty directory
The
Pathlib
module provides different ways to interact with your files. Rmdir is one of the path functions which allows you to delete an empty folder. Firstly, you need to select thePath()
for the directory, callingrmdir()
method will check the folder size. If it’s empty, it’ll delete it.This is a good way to deleting empty folders without any fear of losing actual data.
您可以使用内置的
pathlib
模块(需要 Python 3.4+,但 PyPI 上有旧版本的向后移植:pathlib
,pathlib2
)。要删除文件,可以使用
unlink
方法:或者
rmdir
删除方法空文件夹:You can use the built-in
pathlib
module (requires Python 3.4+, but there are backports for older versions on PyPI:pathlib
,pathlib2
).To remove a file there is the
unlink
method:Or the
rmdir
method to remove an empty folder:对于 Python 3,要单独删除文件和目录,请使用 <代码>取消链接和
rmdir
分别是Path
对象方法:请注意,您还可以将相对路径与
Path
对象一起使用,并且可以使用Path.cwd
检查当前工作目录。要删除 Python 2 中的单个文件和目录,请参阅下面标记的部分。
要删除包含内容的目录,请使用
shutil.rmtree
,请注意,这在 Python 2 和 3 中可用:演示
Python 3.4 中的新功能是
Path
对象。我们用一个来创建一个目录和文件来演示用法。请注意,我们使用
/
来连接路径的各个部分,这可以解决操作系统之间的问题以及在 Windows 上使用反斜杠的问题(您需要将反斜杠加倍,例如\\
或使用原始字符串,例如r"foo\bar"
):现在:
现在让我们删除它们。首先是文件:
我们可以使用 globbing 来删除多个文件 - 首先让我们为此创建几个文件:
然后迭代 glob 模式:
现在,演示删除目录:
如果我们想删除一个目录及其中的所有内容怎么办?
对于此用例,请使用
shutil.rmtree
让我们重新创建目录和文件:
并注意
rmdir
除非为空否则会失败,这就是 rmtree 如此方便的原因:现在,导入 rmtree 并将目录传递给函数:
我们可以看到整个内容已被删除:
Python 2
如果您使用的是 Python 2,则会有一个 向后移植名为pathlib2的pathlib模块,可以使用pip安装:
然后您可以为库添加别名到
pathlib
或者直接导入
Path
对象(如此处所示):如果太多,您可以使用
os.remove
或os.unlink
或者
您可以使用
os 删除目录.rmdir
:注意还有a
os.removedirs
- 它仅递归删除空目录,但它可能适合您的用例。For Python 3, to remove the file and directory individually, use the
unlink
andrmdir
Path
object methods respectively:Note that you can also use relative paths with
Path
objects, and you can check your current working directory withPath.cwd
.For removing individual files and directories in Python 2, see the section so labeled below.
To remove a directory with contents, use
shutil.rmtree
, and note that this is available in Python 2 and 3:Demonstration
New in Python 3.4 is the
Path
object.Let's use one to create a directory and file to demonstrate usage. Note that we use the
/
to join the parts of the path, this works around issues between operating systems and issues from using backslashes on Windows (where you'd need to either double up your backslashes like\\
or use raw strings, liker"foo\bar"
):and now:
Now let's delete them. First the file:
We can use globbing to remove multiple files - first let's create a few files for this:
Then just iterate over the glob pattern:
Now, demonstrating removing the directory:
What if we want to remove a directory and everything in it?
For this use-case, use
shutil.rmtree
Let's recreate our directory and file:
and note that
rmdir
fails unless it's empty, which is why rmtree is so convenient:Now, import rmtree and pass the directory to the funtion:
and we can see the whole thing has been removed:
Python 2
If you're on Python 2, there's a backport of the pathlib module called pathlib2, which can be installed with pip:
And then you can alias the library to
pathlib
Or just directly import the
Path
object (as demonstrated here):If that's too much, you can remove files with
os.remove
oros.unlink
or
and you can remove directories with
os.rmdir
:Note that there is also a
os.removedirs
- it only removes empty directories recursively, but it may suit your use-case.这是我删除目录的功能。 “路径”需要完整路径名。
This is my function for deleting dirs. The "path" requires the full pathname.
Shutil.rmtree 是异步函数,
所以如果你想检查它何时完成,你可以使用 while...loop
shutil.rmtree is the asynchronous function,
so if you want to check when it complete, you can use while...loop
对于删除文件:
或
两个函数在语义上是相同的。此函数删除(删除)文件路径。如果路径不是文件而是目录,则会引发异常。
对于删除文件夹:
或者
为了删除整个目录树,可以使用
shutil.rmtree()
。os.rmdir
仅当目录为空且存在时才有效。对于以递归方式删除父文件夹:
它使用 self 删除每个空父目录,直到父目录有一些内容
有关更多信息,请查看官方文档:
os.unlink
,os.remove
, <一个href="https://docs.python.org/library/os.html#os.rmdir" rel="noreferrer">os.rmdir
、shutil.rmtree
,os.removdirs
For deleting files:
or
Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.
For deleting folders:
or
In order to remove whole directory trees,
shutil.rmtree()
can be used.os.rmdir
only works when the directory is empty and exists.For deleting folders recursively towards parent:
It remove every empty parent directory with self until parent which has some content
For more info check official doc:
os.unlink
,os.remove
,os.rmdir
,shutil.rmtree
,os.removedirs
避免 TOCTOU 问题questions/6996603/how-to-delete-a-file-or-folder#comment99147016_42641792">埃里克Araujo 的评论,您可以捕获异常来调用正确的方法:
由于
shutil.rmtree()
只会删除目录和os.remove()
或 < code>os.unlink() 只会删除文件。To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:
Since
shutil.rmtree()
will only remove directories andos.remove()
oros.unlink()
will only remove files.我个人的偏好是使用 pathlib 对象 - 它提供了一种更Pythonic且更不易出错的方式与文件系统交互,特别是如果您开发跨平台代码。
在这种情况下,您可以使用 pathlib3x - 它提供了最新的(在撰写本答案时 Python 3.10.a0 )Python pathlib for Python 3.6 或更高版本的向后移植,以及一些附加功能,例如“copy”、“copy2” 、“copytree”、“rmtree”等...
它还包装
shutil.rmtree
:您可以在 github 或 PyPi
免责声明:我pathlib3x 库的作者。
My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.
In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...
It also wraps
shutil.rmtree
:you can find it on github or PyPi
Disclaimer: I'm the author of the pathlib3x library.
删除文件夹中的所有文件
删除目录中的所有文件夹
To remove all files in folder
To remove all folders in a directory
有一种简单有效的方法可以使用列表理解删除所有文件和目录。
它的工作原理是这样的:
for f in glob.glob(path.join(your_dir, "*"))
remove(f) if path.isfile(f)
else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]是最 有趣的。
glob
和remove
组合清空它们[remove(ff) for ff in glob.glob(path.join(f , "*"))]
rmdir
来删除它。为此,我们使用了 hack; 列表串联。通过添加 + [rmdir(f)] ,我们强制 python 计算 rmdir(f) ,从而为我们删除目录。中提琴!There is a simple and effective way to remove all files and directories using List Comprehension.
This is what it works:
for f in glob.glob(path.join(your_dir, "*"))
remove(f) if path.isfile(f)
else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]
is the most interesting.glob
andremove
combination[remove(ff) for ff in glob.glob(path.join(f, "*"))]
rmdir
to remove it. To do so, we use a hack; list concatenation. By adding+ [rmdir(f)]
we force python to evaluatermdir(f)
and thus remove the directory for us. Viola!我首选的方法 os.walk 和 os.remove 以及 列表理解:
删除一个中的所有文件目录:
如果您有各种您要删除的目录所有文件:
My prefered method os.walk and os.remove with list comprehension:
To delete all files in one directory:
If you have various directories you want to delete all files:
将文件或目录移动到临时目录下并将其删除。这也将是原子的
Move file or directory under a temp directory and delete it. This will be also atomic