Ads by ProfitSence
Close

Methods of deleting files and folders in python

Last Updated on Wednesday 5th Oct 2022

Some Methods

  • os.remove()
  • rmdir()
  • os.unlink()
  • Path().unlink()

os.remove() Used to delete the file in the specified path

			
					import os
path = 'yourPath/'
file = 'yourPath/someFile.txt'
print('Folder:', os.listdir(path))

try:
    os.remove(file)
except OSError as e:
    print('Delete Problem: ', e)
else:
    print('Sample Folder: ', os.listdir(path))

			
	

rmdir() method-delete empty folders

  • Delete the folder, but the folder must be empty
			
					import os
path = 'yourPath/'
file = 'yourPath/someFolder'
print('Sample Folder:', os.listdir(path))
try:
    os.rmdir(folder)
except OSError as e:
    print('Delete Problem: ', e)
else:
    print('Sample Folder: ', os.listdir(path))

			
	

os.unlink() method - Used to delete the file in the specified path

			
					import os
path = 'sample/'

print('Folder: ', os.listdir(path))
os.unlink('sample/pyFile.py')

print('Sample Folder: ', os.listdir(path))

			
	

Pathlib module Path().unlink() Used to delete the file in the specified path

			
					from pathlib import Path
path = 'sample/'
file = Path('sample/file.txt')
print('Folder: ', os.listdir(path))

try:
    file.unlink()
    print('Sample Folder: ', os.listdir(path))

except OSError as e:
    print (f"Problem: {e.strerror}")