File Handling in Python
File Handling in Python
Python too supports file handling and allows users to handle files i.e., to read
and write files, along with many other file handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of
Python, this concept here is also easy and short. Python treats files differently
as text or binary and this is important. Each line of code includes a sequence of
characters and they form a text file. Each 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 current line and tells the interpreter a new one
has begun.
Working of open() function
Before performing any operation on the file like reading or writing, first, we have
to open that file. For this, we should use Python’s inbuilt function open() but at
the time of opening, we have to specify the mode, which represents the
purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some
data then it will be overridden.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data
and return it as a string:
Python3
print (file.read(5))
The close() command terminates all the resources in use and frees the system
of this particular program.
Python3
file.close()
Example:
Python3
data = file.read()
Python3
f.write("Hello World!!!")
Python3
# Python code to illustrate split() function
data = file.readlines()
word = line.split()
print (word)
There are also various other functions that help to manipulate the files and their
contents. One can explore various other functions in Python Docs.