File handling in python by R4R Team

-Python supports file handling and allow users to handles the file.
-user can easily perform many operation on file like read,write, modification etc.
-the concept of file handling in python was inherit from the other old languages like c,c++.

Open a file-

Syntax-

f=open(filename,mode)

-Here filename is the actual name of the file
-mode means that in what mode you want to open the file like write,read etc.
-here 'f' is the object pointer which refers the starting point of the file, and by using this abject we perform our task.

Close a file-

Syntax-

f.close()

-here 'f' is the object variable of the file so by using close() function we close opening file.

Mode of opening a file-

'r' - for reading the existing file.
'w' - for write into the file, if file not exist then it create by default.
'a' - for append into the file, if file not exist then it create file bydefault, append().
'x' - for create a new file, if same filename exist then it give error.
'rt'- file opening in read text mode.
'rb'- file opening in read binary mode.

Open and close file in different modes-

program-

f=open("myfile.txt",'x')
f.close()
f=open('myfile.txt','r')
f.close()
f=open("myfile.txt",'w')
print(f)
f.close()

output-


<_io.TextIOWrapper name='myfile.txt' mode='w' encoding='cp1252'>


-In this program, we simply open a file in different mode, and 'f' points the file and print(f) it display the object fact and figures.




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!