Delete a file or folder

2019-01-01 03:15发布

问题:

How to delete a file or folder in Python?

回答1:

os.remove() removes a file.

os.rmdir() removes an empty directory.

shutil.rmtree() deletes a directory and all its contents.

pathlib.Path.unlink() removes the file or symbolic link.

pathlib.Path.rmdir() removes the empty directory.



回答2:

Python syntax to delete a file

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.

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


回答3:

Use

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

(See complete documentation on shutil) and/or

os.remove

and

os.rmdir

(Complete documentation on os.)



回答4:

For deleting files:

You can use unlink or remove.

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

Or

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

This functions removes (deletes) the file path. If path is a directory, OSError is raised.

In Python 2, if the path does not exist, OSError with [Errno 2] (ENOENT) is raised. In Python 3, FileNotFoundError with [Errno 2] (ENOENT) is raised. In Python 3, because FileNotFoundError is a subclass of OSError, catching the latter will catch the former.

For deleting folders:

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

rmdir Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.

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

shutil.rmtree Delete an entire directory tree. Path must point to a directory (but not a symbolic link to a directory).

If ignore_errors is true, errors resulting from failed removals will be ignored and if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

See also:

os.removedirs(name)

os.removedirs(name) Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty).

For example, os.removedirs(\'foo/bar/baz\') will first remove the directory \'foo/bar/baz\', and then remove \'foo/bar\' and \'foo\' if they are empty.



回答5:

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


回答6:

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


回答7:

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/excelsiora/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.



回答8:

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


回答9:

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)


回答10:

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)