标签归档:delete-file

Python3项目删除__pycache__文件夹和.pyc文件

问题:Python3项目删除__pycache__文件夹和.pyc文件

从python3项目中清除所有__pycache__ 文件夹和.pyc/.pyo文件的最佳方法是什么?我已经看到多个用户建议pyclean与Debian捆绑在一起的脚本,但这不会删除文件夹。我想要一种简单的方法来将项目推送到我的DVS之前清理项目。

What is the BEST way to clear out all the __pycache__ folders and .pyc/.pyo files from a python3 project. I have seen multiple users suggest the pyclean script bundled with Debian, but this does not remove the folders. I want a simple way to clean up the project before pushing the files to my DVS.


回答 0

您可以使用下一条命令手动进行操作:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

这将递归地删除当前目录中的所有* .pyc文件和__pycache__目录。

You can do it manually with the next command:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

This will remove all *.pyc files and __pycache__ directories recursively in the current directory.


回答 1

当我将pyclean输错为pycclean时,我自己找到了答案:

    No command 'pycclean' found, did you mean:
     Command 'py3clean' from package 'python3-minimal' (main)
     Command 'pyclean' from package 'python-minimal' (main)
    pycclean: command not found

运行py3clean .清理它很好。

I found the answer myself when I mistyped pyclean as pycclean:

    No command 'pycclean' found, did you mean:
     Command 'py3clean' from package 'python3-minimal' (main)
     Command 'pyclean' from package 'python-minimal' (main)
    pycclean: command not found

Running py3clean . cleaned it up very nicely.


回答 2

macOS和Linux

BSD find在macOS上的实现不同于GNU find-这与BSD和GNU find兼容。使用-name和的-ofor -将这个函数放入.bashrc文件中,从全局实现开始。

pyclean () {
    find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
}

然后cd到您要递归清理的目录,然后键入pyclean

GNU仅查找

这是GNU唯一的解决方案(即Linux)解决方案,但是我觉得使用regex会更好一些:

pyclean () {
    find . -regex '^.*\(__pycache__\|\.py[co]\)$' -delete
}

任何使用Python 3的平台

在Windows上,您甚至可能没有find。但是,您可能确实拥有Python 3,从3.4开始,它具有便捷的pathlib模块:

python3 -Bc "import pathlib; [p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]"
python3 -Bc "import pathlib; [p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]"

-B标志告诉Python不要写.pyc文件。(另请参见PYTHONDONTWRITEBYTECODE环境变量。)

上面的滥用列出了对循环的理解,但是使用时python -c,样式是次要的问题。或者,我们可以滥用(例如)__import__

python3 -Bc "for p in __import__('pathlib').Path('.').rglob('*.py[co]'): p.unlink()"
python3 -Bc "for p in __import__('pathlib').Path('.').rglob('__pycache__'): p.rmdir()"

批判答案

最常见的答案是:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

这似乎效率较低,因为它使用了三个过程。find需要一个正则表达式,因此我们不需要单独调用grep。同样,它已经-delete,所以我们并不需要单独调用rm-和违背评论在这里,它只要他们得到凭借正则表达式匹配的清空删除非空目录。

xargs手册页:

find /tmp -depth -name core -type f -delete

在/ tmp目录下或目录下查找名为core的文件并将其删除,但是比上一个示例更有效(因为我们避免了需要使用fork(2)和exec(2)来启动rm,并且不需要额外的xargs流程)。

macOS & Linux

BSD’s find implementation on macOS is different from GNU find – this is compatible with both BSD and GNU find. Start with a globbing implementation, using -name and the -o for or – Put this function in your .bashrc file:

pyclean () {
    find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
}

Then cd to the directory you want to recursively clean, and type pyclean.

GNU find-only

This is a GNU find, only (i.e. Linux) solution, but I feel it’s a little nicer with the regex:

pyclean () {
    find . -regex '^.*\(__pycache__\|\.py[co]\)$' -delete
}

Any platform, using Python 3

On Windows, you probably don’t even have find. You do, however, probably have Python 3, which starting in 3.4 has the convenient pathlib module:

python3 -Bc "import pathlib; [p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]"
python3 -Bc "import pathlib; [p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]"

The -B flag tells Python not to write .pyc files. (See also the PYTHONDONTWRITEBYTECODE environment variable.)

The above abuses list comprehensions for looping, but when using python -c, style is rather a secondary concern. Alternatively we could abuse (for example) __import__:

python3 -Bc "for p in __import__('pathlib').Path('.').rglob('*.py[co]'): p.unlink()"
python3 -Bc "for p in __import__('pathlib').Path('.').rglob('__pycache__'): p.rmdir()"

Critique of an answer

The top answer used to say:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

This would seem to be less efficient because it uses three processes. find takes a regular expression, so we don’t need a separate invocation of grep. Similarly, it has -delete, so we don’t need a separate invocation of rm —and contrary to a comment here, it will delete non-empty directories so long as they get emptied by virtue of the regular expression match.

From the xargs man page:

find /tmp -depth -name core -type f -delete

Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don’t need the extra xargs process).


回答 3

由于这是一个Python 3项目,因此您只需要删除__pycache__目录-所有.pyc/ .pyo文件都在其中。

find . -type d -name __pycache__ -exec rm -r {} \+

或更简单的形式

find . -type d -name __pycache__ -delete

出于某种原因对我不起作用(文件已删除,但目录未删除),因此出于完整性考虑,我将两者都包括在内。


另外,如果在受版本控制的目录中执行此操作,则可以告诉RCS __pycache__递归忽略文件夹。然后,在需要的时刻,只需清理所有被忽略的文件。这可能会更方便,因为可能需要清理的不仅仅是余地__pycache__

Since this is a Python 3 project, you only need to delete __pycache__ directories — all .pyc/.pyo files are inside them.

find . -type d -name __pycache__ -exec rm -r {} \+

or its simpler form,

find . -type d -name __pycache__ -delete

which didn’t work for me for some reason (files were deleted but directories weren’t), so I’m including both for the sake of completeness.


Alternatively, if you’re doing this in a directory that’s under revision control, you can tell the RCS to ignore __pycache__ folders recursively. Then, at the required moment, just clean up all the ignored files. This will likely be more convenient because there’ll probably be more to clean up than just __pycache__.


回答 4

这是我的别名,可与Python 2和Python 3一起使用,.pyc .pyo__pycache__递归方式删除所有文件以及目录。

alias pyclean='find . -name "*.py[co]" -o -name __pycache__ -exec rm -rf {} +'

This is my alias that works both with Python 2 and Python 3 removing all .pyc .pyo files as well __pycache__ directories recursively.

alias pyclean='find . -name "*.py[co]" -o -name __pycache__ -exec rm -rf {} +'

回答 5

如果需要永久解决方案以将Python缓存文件保留在项目目录之外:

Python 3.8开始,您可以使用环境变量PYTHONPYCACHEPREFIX为Python定义一个缓存目录。

从Python文档中:

如果设置了该选项,Python将在此路径的镜像目录树中而不是源树中的pycache目录中写入.pyc文件。这等效于指定-X pycache_prefix = PATH选项。

如果./profile将以下行添加到Linux中:

export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/"

Python不会__pycache__在您的项目目录中创建烦人的目录,而是将所有这些目录放在~/.cache/cpython/

If you need a permanent solution for keeping Python cache files out of your project directories:

Starting with Python 3.8 you can use the environment variable PYTHONPYCACHEPREFIX to define a cache directory for Python.

From the Python docs:

If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in pycache directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.

Example

If you add the following line to your ./profile in Linux:

export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/"

Python won’t create the annoying __pycache__ directories in your project directory, instead it will put all of them under ~/.cache/cpython/


回答 6

我使用的命令:

find . -type d -name "__pycache__" -exec rm -r {} +

说明:

  1. 首先查找__pycache__当前目录中的所有文件夹。

  2. 执行rm -r {} +以上步骤删除每个文件夹({} 表示占位符并+结束命令)

编辑1:

我使用的是Linux,要重用我将以下行添加到~/.bashrc文件中的命令

alias rm-pycache='find . -type d -name  "__pycache__" -exec rm -r {} +'

编辑2: 如果您使用的是VS Code,则无需__pycache__手动删除。您可以将以下代码段添加到settings.json文件中。之后,VS Code将为您隐藏所有__pycache__文件夹

"files.exclude": {
     "**/__pycache__": true
}

希望能帮助到你 !!!

The command I’ve used:

find . -type d -name "__pycache__" -exec rm -r {} +

Explains:

  1. First finds all __pycache__ folders in current directory.

  2. Execute rm -r {} + to delete each folder at step above ({} signify for placeholder and + to end the command)

Edited 1:

I’m using Linux, to reuse the command I’ve added the line below to the ~/.bashrc file

alias rm-pycache='find . -type d -name  "__pycache__" -exec rm -r {} +'

Edited 2: If you’re using VS Code, you don’t need to remove __pycache__ manually. You can add the snippet below to settings.json file. After that, VS Code will hide all __pycache__ folders for you

"files.exclude": {
     "**/__pycache__": true
}

Hope it helps !!!


回答 7

从项目目录中键入以下内容:

删除所有.pyc文件

find . -path "*/*.pyc" -delete

删除所有.pyo文件:

find . -path "*/*.pyo" -delete

最后,要删除所有‘__pycache__’,请输入:

find . -path "*/__pycache__" -type d -exec rm -r {} ';'

如果遇到权限拒绝错误,请在上述所有命令的开头添加sudo

From the project directory type the following:

Deleting all .pyc files

find . -path "*/*.pyc" -delete

Deleting all .pyo files:

find . -path "*/*.pyo" -delete

Finally, to delete all ‘__pycache__’, type:

find . -path "*/__pycache__" -type d -exec rm -r {} ';'

If you encounter permission denied error, add sudo at the begining of all the above command.


回答 8

使用PyCharm

删除Python编译文件

  1. 在中Project Tool Window,右键单击应从中删除Python编译文件的项目或目录。

  2. 在上下文菜单上,选择Clean Python compiled files

.pyc驻留在所选目录中的文件将被静默删除。

Using PyCharm

To remove Python compiled files

  1. In the Project Tool Window, right-click a project or directory, where Python compiled files should be deleted from.

  2. On the context menu, choose Clean Python compiled files.

The .pyc files residing in the selected directory are silently deleted.


回答 9

非常感谢其他答案,基于这些答案,这就是我用于Debian软件包prerm文件的内容:

#!/bin/sh
set -e

deb_package='package-name'
python_package='package_name'

if which pyclean >/dev/null 2>&1; then
    py3clean -p $deb_package
else
    dpkg -L $deb_package | grep ${python_package}$ | while read file
    do
        find ${file} -type d -name __pycache__ -exec rm -r {} \+
    done
fi

Thanks a lot for the other answers, based on them this is what I used for my Debian package’s prerm file:

#!/bin/sh
set -e

deb_package='package-name'
python_package='package_name'

if which pyclean >/dev/null 2>&1; then
    py3clean -p $deb_package
else
    dpkg -L $deb_package | grep ${python_package}$ | while read file
    do
        find ${file} -type d -name __pycache__ -exec rm -r {} \+
    done
fi

回答 10

为什么不只是使用rm -rf __pycache__git add -A然后运行以将其从存储库中删除,然后添加__pycache__/到您的.gitignore文件中。

Why not just use rm -rf __pycache__? Run git add -A afterwards to remove them from your repository and add __pycache__/ to your .gitignore file.


回答 11

请直接到您的终端,然后输入:

$rm __pycache__

它将被删除。

Please just go to your terminal then type:

$rm __pycache__

and it will be removed.


如何删除文件或文件夹?

问题:如何删除文件或文件夹?

如何在Python中删除文件或文件夹?

How to delete a file or folder in Python?


回答 0


PathPython 3.4+ pathlib模块中的对象还公开了这些实例方法:


Path objects from the Python 3.4+ pathlib module also expose these instance methods:


回答 1

Python语法删除文件

import os
os.remove("/tmp/<file_name>.txt")

要么

import os
os.unlink("/tmp/<file_name>.txt")

要么

适用于Python版本> 3.5的pathlib

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok = False)

Unlink方法用于删除文件或符号链接。

如果missing_ok为false(默认值),则在路径不存在时引发FileNotFoundError。
如果missing_ok为true,则将忽略FileNotFoundError异常(与POSIX rm -f命令相同的行为)。
在版本3.8中更改:添加了missing_ok参数。

最佳实践

  1. 首先,检查文件或文件夹是否存在,然后仅删除该文件。这可以通过两种方式实现:
    一。os.path.isfile("/path/to/file")
    b。采用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)

异常处理

#!/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))

预期输出

输入要删除的文件名:demo.txt
错误:demo.txt-没有这样的文件或目录。

输入要删除的文件名:rrr.txt
错误:rrr.txt-不允许操作。

输入要删除的文件名: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))

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version > 3.5

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

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

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. 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:    ## Show an error ##
    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 failed, report it back to 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 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))

回答 2

采用

shutil.rmtree(path[, ignore_errors[, onerror]])

(请参阅关于shutil的完整文档)和/或

os.remove

os.rmdir

(关于os的完整文档。)

Use

shutil.rmtree(path[, ignore_errors[, onerror]])

(See complete documentation on shutil) and/or

os.remove

and

os.rmdir

(Complete documentation on os.)


回答 3

这是同时使用os.remove和的强大功能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))

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))

回答 4

您可以使用内置的pathlib模块(需要Python 3.4+,但也有旧版本PyPI上的反向移植:pathlibpathlib2)。

要删除文件,可以使用以下unlink方法:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

rmdir删除文件夹的方法:

import pathlib
path = pathlib.Path(name_of_folder)
path.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:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

Or the rmdir method to remove an empty folder:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

回答 5

如何在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

请注意,您还可以将相对路径与Path对象一起使用,并且可以使用来检查当前的工作目录Path.cwd

要在Python 2中删除单个文件和目录,请参见下面标记的部分。

要删除包含目录的目录,请使用shutil.rmtree,请注意,该目录在Python 2和3中可用:

from shutil import rmtree

rmtree(dir_path)

示范

Path对象是Python 3.4中的新增功能。

让我们用一个目录和文件来演示用法。请注意,我们使用/来连接路径的各个部分,这解决了操作系统之间的问题以及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()

现在:

>>> file_path.is_file()
True

现在让我们删除它们。首先文件:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

我们可以使用通配符删除多个文件-首先,我们为此创建一些文件:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

然后只需遍历全局模式:

>>> 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

现在,演示删除目录:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

如果我们要删除目录及其中的所有内容怎么办?对于此用例,请使用shutil.rmtree

让我们重新创建目录和文件:

file_path.parent.mkdir()
file_path.touch()

并注意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/username/directory'

现在,导入rmtree并将目录传递给该功能:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

我们可以看到整个内容已被删除:

>>> directory_path.exists()
False

Python 2

如果您使用的是Python 2,则有一个名为pathlib2的pathlib模块的反向端口,可以使用pip进行安装:

$ pip install pathlib2

然后您可以将库别名为 pathlib

import pathlib2 as pathlib

或者直接导入Path对象(如此处所示):

from pathlib2 import Path

如果太多,您可以使用删除文件os.removeos.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

要么

unlink(join(expanduser('~'), 'directory/file'))

您可以使用以下命令删除目录os.rmdir

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

请注意,还有一个os.removedirs-它仅以递归方式删除空目录,但它可能适合您的用例。

How do I delete a file or folder in Python?

For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively:

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

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()

and now:

>>> file_path.is_file()
True

Now let’s delete them. First the file:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

We can use globbing to remove multiple files – first let’s create a few files for this:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

Then just iterate over the glob pattern:

>>> 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

Now, demonstrating removing the directory:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

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:

file_path.parent.mkdir()
file_path.touch()

and note that rmdir fails unless it’s empty, which is why rmtree is so convenient:

>>> 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/username/directory'

Now, import rmtree and pass the directory to the funtion:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

and we can see the whole thing has been removed:

>>> directory_path.exists()
False

Python 2

If you’re on Python 2, there’s a backport of the pathlib module called pathlib2, which can be installed with pip:

$ pip install pathlib2

And then you can alias the library to pathlib

import pathlib2 as pathlib

Or just directly import the Path object (as demonstrated here):

from pathlib2 import Path

If that’s too much, you can remove files with os.remove or os.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

or

unlink(join(expanduser('~'), 'directory/file'))

and you can remove directories with os.rmdir:

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

Note that there is also a os.removedirs – it only removes empty directories recursively, but it may suit your use-case.


回答 6

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)

回答 7

shutil.rmtree是异步函数,因此,如果要检查它是否完成,可以使用while … loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while…loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

回答 8

删除文件:

os.unlink(path, *, dir_fd=None)

要么

os.remove(path, *, dir_fd=None)

这两个功能在语义上是相同的。此功能删除(删除)文件路径。如果path不是文件,而是目录,则会引发异常。

删除文件夹:

shutil.rmtree(path, ignore_errors=False, onerror=None)

要么

os.rmdir(path, *, dir_fd=None)

为了删除整个目录树,shutil.rmtree()可以使用。os.rmdir仅在目录为空且存在时才起作用。

要递归删除父文件夹:

os.removedirs(name)

它用self删除每个空的父目录,直到有一些内容的父目录为止

例如 os.removedirs(’abc / xyz / pqr’)如果目录为空,则会按顺序abc / xyz / pqr,abc / xyz和abc删除目录。

欲了解更多信息检查官方文档:os.unlinkos.removeos.rmdirshutil.rmtreeos.removedirs

For deleting files:

os.unlink(path, *, dir_fd=None)

or

os.remove(path, *, dir_fd=None)

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:

shutil.rmtree(path, ignore_errors=False, onerror=None)

or

os.rmdir(path, *, dir_fd=None)

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:

os.removedirs(name)

It remove every empty parent directory with self until parent which has some content

ex. os.removedirs(‘abc/xyz/pqr’) will remove the directories by order ‘abc/xyz/pqr’, ‘abc/xyz’ and ‘abc’ if they are empty.

For more info check official doc: os.unlink , os.remove, os.rmdir , shutil.rmtree, os.removedirs


回答 9

删除文件夹中的所有文件

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))

回答 10

为了避免ÉricAraujo 的注释突出显示的TOCTOU问题,您可以捕获异常以调用正确的方法:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

因为shutil.rmtree()将仅删除目录,os.remove()或者os.unlink()仅将删除文件。

To avoid the TOCTOU issue highlighted by Éric Araujo’s comment, you can catch an exception to call the correct method:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

Since shutil.rmtree() will only remove directories and os.remove() or os.unlink() will only remove files.


回答 11

subprocess如果您喜欢编写漂亮且易读的代码,那么我建议您使用:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

而且,如果您不是软件工程师,那么可以考虑使用Jupyter。您可以简单地输入bash命令:

!rm -r my_dir

传统上,您使用shutil

import shutil
shutil.rmtree(my_dir) 

I recommend using subprocess if writing a beautiful and readable code is your cup of tea:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

And if you are not a software engineer, then maybe consider using Jupyter; you can simply type bash commands:

!rm -r my_dir

Traditionally, you use shutil:

import shutil
shutil.rmtree(my_dir)