37
loading...
This website collects cookies to deliver better user experience
os
moduleshutil
modulepathlib
moduleos
module is a built-in utility available in both Python 2 and 3 versions, and it provides functions to interact easily with the operating system.os.remove()
is used to remove or delete a file in Python. This method cannot remove a directory, and if you try giving a directory as a path, it throws an OSError.# Import os module
import os
filePath='/Projects/Tryouts/test/python.txt'
# check whethere the provided filepath exists and if its of file type
if os.path.isfile(filePath):
# delete the file using remove function
os.remove(filePath)
print("Successfully deleted a file")
else:
print("File doesn't exists!")
Successfully deleted a file
isFile
or specify an invalid path to the os.remove()
method, Python will throw a FileNotFoundError
as shown below.Traceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 3, in <module>
os.remove(filePath)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '/Projects/Tryouts/test/path_does_not_exsist.txt'
os.rmdir()
method to remove or delete an empty directory. ** If the directory does not exist or is found not empty, you will get an **OSError.isdir
or specify an invalid path to the os.rmdir()
*method, Python will throw a *FileNotFoundError
as shown below.# Import os module
import os
folderPath='/Projects/Tryouts/test/'
# check whethere the provided folder path exists and if its of directory type
if os.path.isdir(folderPath):
# delete the folder using rmdir function
os.rmdir(folderPath)
print("Successfully deleted a folder")
else:
print("Folder doesn't exists!")
Successfully deleted a folder
os
module was you cannot delete an entire directory with contents inside it. If you want to delete a directory and remove all the files inside it recursively, you should use shutil.rmtree()
method.ignore_errors
_are false or omitted, such errors are handled by calling a handler specified by onerror.
# Import os module
import shutil
# Directory that needs to be deleted. Removes all the files and folders inside the path
folderpath='/Projects/Tryouts/test/'
shutil.rmtree(folderpath)
pathlib
module, which comes as a built-in module. This module offers classes representing filesystem paths with semantics appropriate for different operating systems.pathlib
has a method called Path.unlink()
which removes a file or symoblic link.# Import os module
import pathlib
# removes the current file path or symbolic link
file_to_remove= pathlib.Path('/Projects/Tryouts/test/python.txt')
file_to_remove.unlink()
pathlib
has a method called Path.rmdir()
which removes the specified directory. The directory must be empty else it will raise an OSError.# Import os module
import pathlib
# removes the current directory if its empty
folder_to_remove= pathlib.Path('/Projects/Tryouts/test/')
folder_to_remove.rmdir()