File Handling in Python
File Handling in Python
Topperworld.in
File Handling
• Python 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.
Let’s start with the reading and writing files.
©Topperworld
Python Programming
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.
Syntax:
f = open(filename, mode)
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
©Topperworld
Python Programming
SN Access Description
mode
1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access
mode is passed.
3 r+ It opens the file to read and write both. The file pointer exists
at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The
file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The
file pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at
the end of the previously written file if exists any. It creates a
new file if no file exists with the same name.
©Topperworld
Python Programming
11 a+ It opens a file to append and read both. The file pointer remains
at the end of the file if a file exists. It creates a new file if no file
exists with the same name.
12 ab+ It opens a file to append and read both in binary format. The
file pointer remains at the end of the file.
©Topperworld
Python Programming
Output:
Syntax:
1. fileobject.close()
Example:
©Topperworld
Python Programming
Syntax:
Example:
with open("file.txt",'r') as f:
content = f.read();
print(content)
SN Method Description
©Topperworld
Python Programming
7 File.readline([size]) It reads one line from the file and places the file
pointer to the beginning of the new line.
©Topperworld