पिछले topics में आपने पढ़ा की Python में files को कैसे create , update करते हैं। इस topic में आप file / folder को कैसे delete करते हैं वो पढ़ेंगे।


Python में file delete करने के लिए सबसे पहले तो os module को import करना पड़ता है , फिर remove() functions का use करके file को delete किया जाता है।

Python Delete File Example

पिछले topics create की गई mytest.text name से file पड़ी हुई है जिसे delete करने की कोशिश करेंगे।

Copy Fullscreen Close Fullscreen
# first import the module.
import os 
os.remove('mytest.txt')

Check If File Exist

by default अगर remove() function में pass की गयी file नहीं मिली तो error generate होती है
See Example-

import os 
# we already delted this file that's why it will generate an error.
os.remove('mytest.txt')

Traceback (most recent call last):
  File "delete_file.py", line 3, in <module>
    os.remove('mytest.txt')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'mytest.txt'

इसीलिए file delete करने से पहले यह check कर लेना चाहिए कि file exist है या नहीं , exist होने पर ही file को delete करें। file की existence check करने के लिए os module में defined path class का exists() method use किया जाता है।
For Example -

Copy Fullscreen Close Fullscreen Run
# import module.
import os 
"""
Here path is a class.
exists() is a method defined in path class.
"""
if os.path.exists('mytest.txt') : 
  os.remove('mytest.txt')
else :
  print("File doesn't exists.")
Output
C:\Users\Rahulkumar\Desktop\python>python delete_file.py
File doesn't exists.

Python Delete Folder

किसी folder / directory को delete करने के लिए os module में defined rmdir() method का use किया जाता है।
Example -

# import module.
import os 
os.rmdir('myfolder')

भी folder न मिलने पर rmdir() method error generate करता है इसलिए file की तरह ही folder भी check कर ले delete करने से पहले।

Copy Fullscreen Close Fullscreen
# import module.
import os 
if os.path.exists('myfolder') : 
  os.rmdir('myfolder')
else :
  print("Folder doesn't exists.")

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers