Unit 4
Unit 4
(Unit 4)
IV Python File Operations: Reading files, Writing files in python, Understanding read functions,
read(), readline(), readlines(). Understanding write functions, write() and writelines() Manipulating
file pointer using seek Programming, using file operations. 04
File handling in Python (also known as Python I/O) involves the reading and writing process and
many other file handling options. The built-in Python methods can manage two file types, text and
binary files, but they encode data differently.
A text file consists of a series of lines. And each text line consists of several characters. The end of
the line (EOL) signifies the ending of each line in a text file. There are several special characters
used as EOL, but the most common are comma {,} and new lines.
Take an example to understand the standard steps used during File Handling in Python.
Opening a file to write.
• Appending and writing to a file.
• Closing a file
Why File Handling Is Important In Python?
The concept of file handling can also use in other programming languages, but it is complicated or
time-consuming. Unlike other programming languages, it is easy to implement Python file handling.
Also, it is important to know how to read the data from a given file whenever you want to analyses
the data. All of these make the file handling concept extremely important.
Python offers built-in functions to open, write, read, close and delete files. Let us start by opening a
file.
Open a file in Python
To read or write to a file, you must first open it. The built-in Python function open() used to open a
file. This function takes two arguments, one file name, and the other mode (read mode, write mode)
to open the file. It returns a file object that is used together with different functions. We use the
following syntax to open a file in python.
Syntax of the Python open function:
file object = open(file_name [, access_mode][, buffering])
Below are the parameter details.
A file is a named location used for storing data. For example, main.py is a file that is always used to
Python provides various functions to perform different file operations, a process known as File
Handling.
In Python, we need to open a file first to perform any operations on it—we use the open() function to
file1 = open("file1.txt")
Here, we have created a file object named file1. Now, we can use this object to work with files.
After we open a file, we use the read() method to read its content. For example,
Output
In the above example, the code file1.read() reads the content of the file and stores it in
To write to a Python file, we need to open it in write mode using the w parameter.
When we run the above code, we will see the specified content inside the file.
When we are done performing operations on the file, we need to close the file properly. We use
the close() function to close a file in Python. For example,
# open a file
file1 = open("file1.txt", "r")
Output
Note: Closing a file will free up the resources that are tied to the file. Hence, it is a good
In Python, there is a better way to open a file using with...open. For example,
Output
Here, with...open automatically closes the file, so we don't have to use the close() function.
Python file modes
When working with the Python file, you have to use modes for specific operations such as creating,
reading, writing, adding etc. It referred to Python file modes in file handling.
Modes Description
rb+ Opens a file for both reading and writing in binary format.
wb+ Opens a file for both writing and reading in binary format.
ab+ Opens a file for both appending and reading in binary format.
Take a look at this program and analyse how the reading mode works:
1 # a file named "file", will be opened with the reading mode.
5 print (each)
The open command opens the file in reading mode and prints each line of the file with for loop.
In Python, there is more than one way to read a file. If you need to extract a string with all of the
characters in the file, we can use the.read(). The entire code works like this:
1 # Python code to illustrate read() mode
3 print (file.read())
Another way to read a file is to call a number of characters like in the code below. The interpreter
will read and return the first five characters of the stored data as a string:
1 # Python code to illustrate read() mode character wise
3 print (file.read(5))
When you call the Python open() function, an object that is the filehandle is returned. You should
also know that Python files have several attributes linked. And we can use the file handle to list the
file attributes.
Please run through the table below to learn more about the file attributes.
Attribute Description
Returns a boolean to suggest if a space char is added in the output <print> command
<file.softspace>
before it is printed another values.
3 Opening mode: wb
4 Softspace flag: 0
First of all, open it with a mode (read/write/append) while you are ready to enter data to a file.
You can even do the same with the mode append. If you have also used the <w> mode, the existing
data from the file will delete. It would help if you, therefore, took note of this fact when you choose
it.
The write() file method
Python provides a write() method to write a string or bytes sequence to a file. This function returns a
number that is the size of data stored in a single Write call.
Example: Read/Write to a File in Python
1 # Python code to create a file
2 file = open('file.txt','w')
5 file.close()
The close() command ends all used resources and frees the system from the specific program.
In the above example, the statement f=open(―file.txt‖, ―w‖) opens file.txt in write mode, returns the
file object and assigns it to the variable f in the open method. ―w‖ specifies the writable file. Next,
we‘ve got to put some data into the file. In the file, a string saved in the file.write(―Hello! Python‖).
Finally, file.close() closes the object file.
You find ―file.txt‖ created on your computer when you run the above code. You can view the
contents by opening an editor, such as Notepad.
Python provides the writelines() method for saving the contents of the list object in a file. Since the
character of the new line is not automatically written to the file, the character must be given in the
string.
Example: Write Lines to File
1 lines=["Hello world.\n", "Welcome to Technology.\n"]
2 f=open("D:\file.txt","w")
3 file.writelines(lines)
4 file.close()
Say, if there is an exception during certain operations on the file. In this case, the code leaves the file
without closing. It‘s, therefore, better to insert the code into a <try-finally> block.
1 try:
3 # do file operations.
4 finally:
5 file.close()
Even if there is an exception, the above code ensures that your file is closed properly.
Auto close using ‘with’
The WITH clause is another way of closing a file. It ensures that when the block executes within the
WITH clause, the file is closed. The beauty of this method is that the close() method does not need to
call explicitly.
1 with open('app.log', encoding = 'utf-8') as file:
First of all, to read data from a file, you need to open it in reading mode. You can then call any of the
Python methods for reading from a file.
Three different methods have provided to read file data.
• readline():
read characters from the current reading position to the newline character.
• read(chars): reads the number of characters that are specified starting from the current position.
• readlines(): reads all lines until file end and returns an object list.
Usually, we use Python <read(size)> to read the file content up to the size. If you don‘t pass the size,
then the whole file will read.
Example: Read from a File in Python
1 with open('app.log', 'w', encoding = 'utf-8') as f:
9 #'file\n'
13 #''
2 line = file.readline()
3 print(line)
4 file.close()
We must open the file in ‗r‘ mode. The readline() method returns the first line and points to the
second line in the file.
Use the While Loop to read all lines from a file, as shown below.
Example: Reading Lines
1 file = open("D:\file.txt","r")
2 line = file.readline()
3 while line!='':
4 print(line)
5 line = file.readline()
Working of append() mode
2 file = open('file.txt','a')
4 file.close()
There are also several other commands in File handling used to handle multiple tasks such as:
1 Rstrip(): This function removes spaces from the right side for each line of a file.
2 Lstrip(): This function removes spaces from the left side of each file line.
It is intended to provide much cleaner syntax and exceptions handling when working with code. It
explains why it is good to practise, if applicable, to use them with a statement. It is useful because any
opened files will be automatically closed after one is done automatically by this method.
Example:
1 # Python code to illustrate with()
3 data = file.read()
3 file.write("Hello World!!!")
We can also split lines with Python file handling. This splits the variable when there is space. You
can split by any character as we like. The code is here:
1 # Python code to illustrate split() function
3 data = file.readlines()
5 word = line.split()
6 print (word)
Seek() Method
Use the seek() function to set the current read/write position to read or write at a certain position.
Syntax:
file.seek(offset[, from])
The <offset> argument represents the size of the displacement.
The <from> argument indicates the start point.
If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the current position.
It from is 2, then the end of the file would serve as the reference position.
Assuming that file.txt contains ―Hello World‖ text, the following example demonstrates the seek()
method.
Example: seek()
1 file = open("D:\file.txt","r+")
2 file.seek(6,0)
3 lines = file.readlines()
5 print(line)
6 file.close()
Function Description
<file.close()> Close the file. You must reopen it for additional access.
<file.flush()> Flush the internal buffer. It‘s same as the <stdio>‘s <fflush()> function.
<file.read(size)> Reads the given no. of bytes. It may read less if EOF is hit.
Text books:
1. Wesley J. Chun, ―Core Python Applications Programming‖, 3rd Edition , Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage
Learning publication
4. Jeeva Jose &P.SojanLal, ―Introduction to Computing and Problem Solving with PYTHON‖,
Khanna Publishers, New Delhi,
2016
5. Downey, A. et al., ―How to think like a Computer Scientist: Learning with Python‖, John Wiley,
2015
6. Mark Lutz, ―Learning Python‖, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739
7. John Zelle, ―Python Programming: An Introduction to Computer Science‖, Second edition, Course
Technology Cengage
8. Michel Dawson, ―Python Programming for Absolute Beginers‖ , Third Edition, Course Technology
Cengage Learning
9. David Beazley, Brian Jones., ―Python Cookbook‖, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377