What is File Handling in Python
File handling is allowing the users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.
In Python, the files are treated as text or binary. Every line of a file is terminated with a special character, called the EOL or End of Line characters like comma or newline character. It ends the present line and tells the interpreter a brand new one has begun.
The open() function in Python to open a file in read or write mode.
open( ) will return a file object.
The syntax : open(filename, mode).
There are three kinds of mode. These shows how files can be opened:
- r , for reading.
- w , for writing.
- a , for appending.
- r+ , for both reading and writing
file = open('test.txt', 'r') for i in file: print (i)
If you need to extract a string that contains all characters in the file, then we can use file.read()
file = open("test.txt", "r") print (file.read())
The write() mode will write to an existing file, or create a new file and write the contents to the new file.
file = open('test.txt','w') file.write("Sample command") file.close() #close() command terminates all the resources in use and frees #the system of this particular program