Comment supprimer un fichier ou un dossier dans Python

Mots clés : pythonfile-iodirectorydelete-filepython

meilleur 4 Réponses Comment supprimer un fichier ou un dossier dans Python

vote vote

97

import os os.remove("/tmp/<file_name>.txt") 
import os os.unlink("/tmp/<file_name>.txt") 
file_to_rem = pathlib.Path("/tmp/<file_name>.txt") file_to_rem.unlink() 
#!/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)) 
 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() 
#!/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)) 
vote vote

86

shutil.rmtree(path[, ignore_errors[, onerror]]) 
os.remove 
os.rmdir 
vote vote

75

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

66

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

Questions similaires