删除文件或文件夹

本文翻译自:Delete a file or folder

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


#1楼

参考:https://stackoom.com/question/TM8R/删除文件或文件夹


#2楼

Create a function for you guys. 为你们创造一个功能。

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

#3楼

Python syntax to delete a file 用于删除文件的Python语法

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

Or 要么

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

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. 使用exception handling.

EXAMPLE for os.path.isfile 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 用于删除文件夹的Python语法

shutil.rmtree()

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

#4楼

You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib , pathlib2 ). 您可以使用内置的pathlib模块(需要Python 3.4+,但在PyPI上有旧版本的pathlibpathlibpathlib2 )。

To remove a file there is the unlink method: 要删除文件,请使用unlink方法:

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

Or the rmdir method to remove an empty folder: 或者删除文件夹的rmdir方法:

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

#5楼

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)

#6楼

How do I delete a file or folder in Python? 如何在Python中删除文件或文件夹?

For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively: 对于Python 3,要分别删除文件和目录,请分别使用unlinkrmdir 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

Note that you can also use relative paths with Path objects, and you can check your current working directory with Path.cwd . 请注意,您还可以使用具有Path对象的相对路径,并且可以使用Path.cwd检查当前的工作目录。

For removing individual files and directories in Python 2, see the section so labeled below. 要删除Python 2中的单个文件和目录,请参阅下面标记的部分。

To remove a directory with contents, use shutil.rmtree , and note that this is available in Python 2 and 3: 要删除包含内容的目录,请使用shutil.rmtree ,并注意这在Python 2和3中可用:

from shutil import rmtree

rmtree(dir_path)

Demonstration 示范

New in Python 3.4 is the Path object. Python 3.4中的新功能是Path对象。

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" ): 请注意,我们使用/来连接路径的各个部分,这解决了操作系统之间的问题以及在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()

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: 我们可以使用globbing删除多个文件 - 首先让我们为此创建一些文件:

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

Then just iterate over the glob pattern: 然后迭代遍历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

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 对于此用例,请使用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: 并注意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'

Now, import rmtree and pass the directory to the funtion: 现在,导入rmtree并将目录传递给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 Python 2

If you're on Python 2, there's a backport of the pathlib module called pathlib2 , which can be installed with pip: 如果您使用的是Python 2,则会有一个名为pathlib2的pathlib模块backport ,可以使用pip进行安装:

$ pip install pathlib2

And then you can alias the library to pathlib 然后你可以将库别名为pathlib

import pathlib2 as pathlib

Or just directly import the Path object (as demonstrated here): 或者直接导入Path对象(如此处所示):

from pathlib2 import Path

If that's too much, you can remove files with os.remove or os.unlink 如果这太多了,您可以使用os.removeos.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 : 你可以用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. 请注意,还有一个os.removedirs - 它只是递归地删除空目录,但它可能适合您的用例。

发布了0 篇原创文章 · 获赞 136 · 访问量 83万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105192685