Unit - File Handling in Python
Unit - File Handling in Python
File handling in Python is a powerful and versatile tool that can be used to perform a
wide range of operations. However, it is important to carefully consider the advantages
and disadvantages of file handling when writing Python programs, to ensure that the code
is secure, reliable, and performs well.
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. Let’s start with the reading and writing files.
Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform
different operations on files (e.g. read, write, append, etc.
User–friendly: Python provides a user-friendly interface for file handling, making it
easy to create, read, and manipulate files.
Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
Hello world
GeeksforGeeks
123 456
f = open(filename, mode)
There is more than one way to read a file in Python. Let us see how we can read the
content of a file in read mode.
Example 1: The open command will open the file in the read mode and the for loop will
print each line present in the file.
Python3
# a file named "geek", will be opened with the reading mode.
print (each)
Output:
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in the file
then we can use file.read().
Python3
print (file.read())
Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with statement.
Python3
data = file.read()
print(data)
Output:
Hello world
GeeksforGeeks
123 456
Example 4: 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))
Output:
Hello
Example 5:
We can also split lines while reading files in Python. The split() function splits the
variable when space is encountered. You can also split using any characters as you wish.
Python3
data = file.readlines()
word = line.split()
print (word)
Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Just like reading a file in Python, there are a number of ways to write in a file in Python.
Let us see how we can write the content of a file using the write() function in Python.
Example 1: In this example, we will see how the write mode and the write() function is
used to write in a file. The close() command terminates all the resources in use and frees
the system of this particular program.
Python3
# Python code to create a file
file = open('geek.txt','w')
file.close()
Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.
Python3
f.write("Hello World!!!")
Output:
Hello World!!!
Example: For this example, we will use the file created in the previous example.
Python3
file.close()
Output:
This is the write commandIt allows us to write in a particular
fileThis will add this line
The readline() method in Python is used to read a single line from a file that has
been opened for reading. When readline() is used in the code, it reads the next
line of the file and returns it as a string.
In this example, we are reading data line by line from a file named test.txt and
printing it into the terminal.
Python3
line = file.readline()
# Loop through the rest of the file and print each line
while line:
print(line)
line = file.readline()
file.close()
Test file
Output:
--------------------------------- END OF LAB RECORD WRITE UP ----------------------------
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n
specified, reads the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For
specified n, reads at most n bytes. However, does not reads more than one
line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string
element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
Example:
Python3
# Creating a file
# readlines function
print(file1.readlines())
print()
file1.close()
Output:
Output of Readlines function is
Hello
This is Delhi
This is Paris
This is London
With statement
with statement in Python is used in exception handling to make the code
cleaner and much more readable. It simplifies the management of common
resources like file streams. Unlike the above implementations, there is no need
to call file.close() when using with statement. The with statement itself ensures
proper acquisition and release of resources.
Syntax:
with open filename as file:
Python3
# Creating a file
file1.write("Hello \n")
file1.writelines(L)
print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Python provides inbuilt functions for creating, writing and reading files. There are two
types of files that can be handled in python, normal text files and binary files (written in
binary language, 0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine-understandable binary language.
Table of content
Access mode
Opening a file
Closing a file
Writing to file
Appending to a file
With statement
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how
the file will be used once it’s opened. These modes also define the location of the File
Handle in the file. File handle is like a cursor, which defines from where the data has to
be read or written in the file. Different access modes for reading a file are –
1. Write Only (‘w’) : Open the file for writing. For an existing file, the data is truncated
and over-written. The handle is positioned at the beginning of the file. Creates the file
if the file does not exist.
2. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file,
data is truncated and over-written. The handle is positioned at the beginning of the
file.
3. Append Only (‘a’) : Open the file for writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted
at the end, after the existing data.
Opening a File
It is done using the open() function. No module is required to be imported for this
function. Syntax:
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the python program file else, full address of
the file should be written on place of filename. Note: The r is placed before filename to
prevent the characters in filename string to be treated as special character. For example, if
there is \temp in the file address, then \t is treated as the tab character and error is raised
of invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not
being placed.
Python3
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used
at the time when the file is no longer needed or if it is to be opened in a different file
mode. Syntax:
File_object.close()
Python3
file1.close()
Writing to file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
1. writelines() : For a list of string elements, each string is inserted in the text file. Used
to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes. Example:
Python3
# Python program to demonstrate
# writing to file
# Opening a file
s = "Hello\n"
file1.write(s)
# at a time
file1.writelines(L)
# Closing file
file1.close()
# Checking if the data is
print(file1.read())
file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data. Let’s see the
below example to clarify the difference between write mode and append mode.
Python3
file1.writelines(L)
file1.close()
# Append-adds at last
file1.write("Today \n")
file1.close()
print(file1.read())
print()
file1.close()
# Write-Overwrites
file1.write("Tomorrow \n")
file1.close()
print()
file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today
With statement
with statement in Python is used in exception handling to make the code cleaner and
much more readable. It simplifies the management of common resources like file
streams. Unlike the above implementations, there is no need to call file.close() when
using with statement. The with statement itself ensures proper acquisition and release of
resources.
Syntax:
with open filename as file:
Python3
# Writing to file
file1.write("Hello \n")
file1.writelines(L)
print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Python3
data = ['This is the first line', 'This is the second line', 'This is the third
line']
f.write(line + '\n')
print(line)
Output
This is the first line
This is the second line
This is the third line
File Pointer positions
Python provides the tell() method which is used to print the byte number at which the
file pointer currently exists. The tell() methods is return the position of read or write
pointer in this file. The syntax of tell() method is given below -
1. fileobject.tell()
Here we give an example for how to find file pointer position in Python. Here we use
tell() method and it is return byte number. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -
A file handle or pointer denotes the position from which the file contents
will be read or written. File handle is also called as file pointer or cursor.
For example, when you open a file in write mode, the file pointer is placed at the
0th position, i.e., at the start of the file. However, it changes (increments) its
position as you started writing content into it.
Or, when you read a file line by line, the file pointer moves one line at a time.
Sometimes we may have to read only a specific portion of the file, in such cases
use the seek() method to move the file pointer to that position.
For example, use the seek() function to do the file operations like: –
Syntax:
f.seek(offset, whence)
How many points the pointer will move is computed from adding offset to a
reference point; the reference point is given by the whence argument.
f.seek(5) Move file pointer five characters ahead from the beginning of a file.
f.seek(5, 1) Move file pointer five characters ahead from the current position.
f.seek(-5, 1) Move file pointer five characters behind from the current position.
f.seek(-5, 2) Move file pointer in the reverse direction. Move it to the 5th character from the end of the file
Seek Operation Meaning
Example
Consider the following example where we are reading a text file contents with
the offset as 6. It means we will start reading the file directly from the
6th character.
text file
Output
First line
Second line
Third line
Fourth line
Fifth line
Sixth line
Seventh line
Eighth line