If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
पिछले topics में आपने पढ़ा की Python में files को कैसे create , update करते हैं। इस topic में आप file / folder को कैसे delete करते हैं वो पढ़ेंगे।
Python में file delete करने के लिए सबसे पहले तो os module को import करना पड़ता है , फिर remove() functions का use करके file को delete किया जाता है।
पिछले topics create की गई mytest.text name से file पड़ी हुई है जिसे delete करने की कोशिश करेंगे।
# first import the module.
import os
os.remove('mytest.txt')
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 -
# 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.")
C:\Users\Rahulkumar\Desktop\python>python delete_file.py File doesn't exists.
किसी 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 करने से पहले।
# import module.
import os
if os.path.exists('myfolder') :
os.rmdir('myfolder')
else :
print("Folder doesn't exists.")
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook