create a new text file in python by R4R Team

-There are many mode in which we open the file for performing a task on file.
-So to create a new file, file handling in python provide seprate mode for doing this.

'x' is the mode in which we open or create a new file.

Syntax-

f=open('myfile.txt','x')

-It will give error, if the file of same file exist.


program-

#create a new file
f=open("new_file.txt",'x')
f.write("Data inside new file")
f.close()

#read file
f=open('new_file.txt','r')
print(f.read())
f.close()


output-

Data inside new file


-In this program, we create a new file named as 'new_file.txt' and write the data 'Data inside new file', then we read the file.

-If we try to create this file again like-

program-

#create a new file
f=open("new_file.txt",'x')
f.close()


output-

f=open("new_file.txt",'x')

FileExistsError: [Errno 17] File exists: 'new_file.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!