-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.