- To remove or delete the existing file, python provides os commands.
- If we have a file named as 'myfile.txt' and we want to delete this file then,
Syntax-
import os
os.remove('myfile.txt')
program-
import os
#create file and insert data
f=open("myfile.txt",'x')
f.write("This is the file")
f.close()
#read that file
f=open('myfile.txt','r')
print(f.read())
f.close()
#delete that file
os.remove('myfile.txt')
#read file to check file is deleted or not
try:
f=open('mytext.txt','r')
print(f.read())
f.close()
except:
print("File not exist")
This is the file
File not exist
import os
#here myfile.txt not exist but still we delete then-
os.remove('myfile.txt')
os.remove('myfile.txt')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'myfile.txt'