Tutorials  Articles  Notifications  Login  Signup


DG

Dhirendra Gupta

Student at BIT Mesra Aug. 4, 2020, 6:37 p.m. ⋅ 1202 views

Python Delete file or directory


To delete a file or folder using python, we must import os. Os library provides remove() function which we can use to delete any file. We can use rmdir() function to delete any directory.

Deleting a file

To delete a file having name hackersfriend.txt from current directory, we can write following code:

import os
os.remove("hackersfriend.txt")

#This will delelte hackersfriend.txt file from current directory

However, you should check if a file exists before attempting to delete it.

import os
if os.path.exists("hackersfriend.txt"):
  os.remove("hackersfriend.txt")
else:
  print("hackersfriend.txt does not exist in current directory")

 

Deleting a directory

To delete a directory we can use rmdir() function like this:

import os
os.rmdir("hackersfriend")

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account