10 examples of 'python delete file if exist' in Python

Every line of 'python delete file if exist' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
133def delete_file(path, name):
134 """ 删除文件 """
135 filename= '/'.join([current_app.static_folder, path, name])
136 if not os.path.exists(filename):
137 return False
138 os.remove(filename)
139 return True
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

45def delete_file(file_name):
46 print("Deleting File: " + file_name)
47
48 # Try to delete the file or folder
49 try:
50 if (os.path.isdir(file_name)):
51 shutil.rmtree(file_name)
52 else:
53 os.remove(file_name)
54 except OSError as e:
55 print("Error deleting file")
56 print(e)
76def delete_file(filename):
77 if os.path.isfile(filename) is True:
78 os.remove(filename)
47def delete_files(file_name):
48 '''
49 Common function to delete generated temporary files
50 '''
51 my_dir = "./"
52 for fname in os.listdir(my_dir):
53 if fname.startswith(file_name):
54 os.remove(os.path.join(my_dir, fname))
146def remove_file_if_exists(filename):
147 """
148 Remove the file if it exists
149
150 :param filename: The file to remove
151 :return: None
152 """
153 try:
154 os.remove(filename)
155 except:
156 pass
784def RemoveFile(path):
785 error = None
786 try:
787 os.remove(path)
788 except OSError as error:
789 print("Exception removing file" + path + " Error Code: " +
790 str(error.errno) + " Error: " + error.strerror, file=sys.stderr)
791 LG().Log('ERROR', "Exception removing file" + path +
792 " Error Code: " + str(error.errno) + " Error: " + error.strerror)
793 return error
794 except IOError as error:
795 print("Exception removing file" + path + " Error Code: " +
796 str(error.errno) + " Error: " + error.strerror, file=sys.stderr)
797 LG().Log('ERROR', "Exception removing file" + path +
798 " Error Code: " + str(error.errno) + " Error: " + error.strerror)
799 return error
800 return error
664def rmfile(filename):
665 if os.path.exists(filename):
666 os.remove(filename)
85def _remove_if_exists(path):
86 if os.path.exists(path):
87 if os.path.isfile(path):
88 os.remove(path)
89 else:
90 shutil.rmtree(path)
22def remove_file(path):
23 try:
24 os.remove(path)
25 except Exception as e:
26 logger.warn("problem removing: " + path)
27 logger.debug(e)
11def delete(path):
12 if os.path.isdir(path):
13 shutil.rmtree(path)
14 else:
15 os.unlink(path)

Related snippets