Categories
delete-file directory file-io python

How do I delete a file or folder in Python?

3004

How do I delete a file or folder?

0

    4406


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

    8

    • 8

      os.rmdir() on Windows also removes directory symbolic link even if the target dir isn’t empty

      Dec 18, 2015 at 17:23

    • 70

      If the file doesn’t exist, os.remove() throws an exception, so it may be necessary to check os.path.isfile() first, or wrap in a try.

      – user1142217

      Jul 4, 2018 at 0:00

    • 21

      just for completion… the exception thrown by os.remove() if a file doesn’t exist is FileNotFoundError.

      – PedroA

      Feb 4, 2020 at 17:52

    • Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file?

      May 9, 2020 at 23:57

    • 10

      @Jérôme I think missing_ok=True, added in 3.8 solves that!

      – Felix

      Dec 8, 2020 at 21:04

    574

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

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

    3

    105

    Use

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

    (See complete documentation on shutil) and/or

    os.remove
    

    and

    os.rmdir
    

    (Complete documentation on os.)

    1

    • 8

      Please add the pathlib interface (new since Python 3.4) to your list.

      – Paebbels

      Apr 25, 2016 at 19:38