DG

dhirendra_gupta

Student at BIT Mesra Aug. 4, 2020, 6:37 p.m. ⋅ 124 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")

 



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details