Delete a file , file handling in python by R4R Team

- 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")


output-

This is the file
File not exist


-In this program, initially we create a file and insert data and read the file, then we delete the file by os.remove('myfile.txt'), then we again try to read that not existing file that's by try and except block are insert so that program will not give any error.

-If we try to delete this file again then-

program-

import os
#here myfile.txt not exist but still we delete then-
os.remove('myfile.txt')


output-

os.remove('myfile.txt')

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'myfile.txt'




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!