Python
File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Some of Different types of Binary Files
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Why we need file handling ?
Check the below program
Output
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
This information ( name and age ) will be not stored
permanently, this information will be lost when u close
your editor or computer.
If you want to store data permanently there are two ways
to store
1.File Handling
2.Database
So in this session we will discuss about the files, later we
will discuss on Database
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
What are access Modes ?
The access mode parameter in the open() function
primarily mentions the purpose of opening the file or the
type of operation we are planning to do with the file after
opening. in Python, the following are the different
characters that we use for mentioning the file opening
modes.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Steps For Opening File in Python
To open a file in Python, Please follow these steps:
Step 1)Find the path of a file
We can open a file using both relative path and absolute path. The path
is the location of the file on the disk.
An absolute path contains the complete directory list required to locate
the file.
A relative path contains the current directory and then the file name.
Step 2)Decide the access mode
The access mode specifies the operation you wanted to perform on the
file, such as reading or writing. To open and read a file, use the r access
mode. To open a file for writing, use the w mode.
Step 3)Pass file path and access mode to the open() function
fp= open(r"File_Name", "Access_Mode"). For example, to open and
read: fp = open('sample.txt', 'r')
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Step 4)Read content from a file.
Next, read a file using the read() method. For example, content =
fp.read(). You can also use readline(), and readlines()
Step 5)Write content into the file
If you have opened a file in a write mode, you can write or
append text to the file using the write() method. For example,
fp.write('content'). You can also use the writeline() method.
Step 6)Close file after completing operation
We need to make sure that the file will be closed properly after
completing the file operation. Use fp.close() to close a file.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example for opening a file and reading the contents of the
file using relative path( python file and text file in same
folder)
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example for opening a file and reading the contents of the
file using absolute path( python file and text file in other
folders)
My Python File location = C:\CMRapp\MyPackage
My Text file = C:\Users\Admin\Desktop
Please Note:
The above file structure is in my Laptop, yours File path
will be different
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Handling the FileNotFoundError
The above code is not handled the FileNotFoundError
exception
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Code with handling FileNotFoundError
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
File open() function
Python provides a set of inbuilt functions available in the
interpreter, and it is always available. We don’t have to
import any module for that. We can open a file using the
built-in function open().
Syntax of the file open() function
The above function will return the file object which we can use to
read or write to a file. Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example we are having a file called ‘students.txt’ and we
are opening the file for reading its contents.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Opening a File in Write Mode
We can open a file for writing new contents into a file using
the open() function with w as the access mode. The cursor
or the file pointer will be placed at the beginning of the file.
Note: If the file is already present it will truncate the file,
which means all the content previously in the file will be
deleted, and the new content will be added to the file.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Opening a File in Append Mode
We can append some content at the end of the file using
the open() function by passing the character a as the access
mode. The cursor will be placed at the end of the file, and
the new content will get added at the end.
The difference between this and the write mode is that the
file’s content will not be truncated or deleted in this mode.
Consider that the file “sample2.txt” is already created and
there is some content in the file. Now we are opening the
file in the append mode and trying to add some content at
the end of the file.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Closing a File
We need to make sure that the file will be closed properly after
completing the file operation. It is a bad practice to leave your
files open.
In Python, It is very important to close a file once the job is done
mainly for the following reasons: –
It releases the resources that have been tied up with the file. By
this space in the RAM can be better utilized and ensures a better
performance.
It ensures better garbage collection.
There is a limit to the number of open files in an application. It is
always better to close the file to ensure that the limit is not
crossed.
If you open the file in write or read-write mode, you don’t know
when data is flushed.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
A file can be closed just by calling the close() function as
follows.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Creating a new file
We can create a new file using the open() function by
setting the x mode. This method will ensure that the file
doesn’t already exist and then create a new file. It will raise
the FileExistsError if the file already exists.
Example: Creating a new file.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
II ) Reading a file
In Python, temporary data that is locally used in a module
will be stored in a variable. In large volumes of data, a file
is used such as text and CSV files and there are methods in
Python to read or write data in those files.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Different modes for reading the file
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
To read a file, Please follow these steps:
Step 1 : Find the path of a file
We can read a file using both relative path and absolute path. The path
is the location of the file on the disk.
An absolute path contains the complete directory list required to locate
the file.
A relative path contains the current directory and then the file name.
Step 2 : Open file in Read Mode
To open a file Pass file path and access mode to the open() function.
The access mode specifies the operation you wanted to perform on the
file, such as reading or writing. For example, r is for reading.
For example, fp= open(r'File_Path', 'r')
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Step 3: Read content from a file.
Once opened, we can read all the text or content of the file
using the read() method. You can also use the readline() to
read file line by line or the readlines() to read all lines.
For example, content = fp.read()
Step 4 :Close file after completing the read operation
We need to make sure that the file will be closed properly
after completing the file operation. Use fp.close() to close a
file.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Example: Read a Text File
The following code shows how to read a text file in Python.
A text file (flatfile) is a kind of computer file that is
structured as a sequence of lines of electronic text.
In this example, we are reading all content of a file using
the absolute Path.
Consider a file “read_demo.txt.”
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
An absolute path contains the entire path to the file or directory
that we need to access. It includes the complete directory list
required to locate the file.
For example, C:\demo\read_demo.txt is an absolute path to
discover the read_demo.txt. All of the information needed to
find the file is contained in the path string.
While opening a file for reading its contents we have always
ensured that we are providing the correct path. In case the file
not present in the provided path we will get FileNotFoundError.
We can avoid this by wrapping the file opening code in the try-
except-finally block.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Reading a File Using the with Statement
We can open a file using the with statement along with the open
function. The general syntax is as follows.
The following are the main advantages of opening a file using ‘with’
statement
The with statement simplifies exception handling by encapsulating
common preparation and cleanup tasks.
This also ensures that a file is automatically closed after leaving the
block.
As the file is closed automatically it ensures that all the resources that
are tied up with the file are released.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
File Read Methods
Python provides three different methods to read the file.
We don’t have to import any module for that.. Below are
the three methods
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
1) readline(): Read a File Line by Line
Using the readline() method, we can read a file line by line.
by default, this method reads the first line in the file.
For example, If you want to read the first five lines from a
text file, run a loop five times, and use the readline()
method in the loop’s body. Using this approach, we can
read a specific number of lines.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Here n represents the number of bytes to read from the file.
This method will read the line and appends a newline
character “\n” to the end of the line. While reading a text
file this method will return a string.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
2) Reading First N lines From a File Using readline()
We can read the first few set of lines from a file by using
the readline() method. Run a loop fo n times using for loop
and range() function, and use the readline() method in the
loop’s body.
Example:
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
III) Reading Entire File Using readline()
We can use the readline() method to read the entire file
using the while loop. We need to check whether the pointer
has reached the End of the File and then loop through the
file line by line.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Python Write to File ( writing data into a file)
Access mode specifying the purpose of opening a file.
Whenever we need to write text into a file, we have to open the
file in one of the specified access modes. We can open the file
basically to read, write or append and sometimes to do multiple
operations on a single file.
To write the contents into a file, we have to open the file in write
mode. Open a file using the built-in function called open(). This
function takes two parameters, namely filename, and access
mode, and returns the file pointer.
We can open a file for modifying or overwrite its contents by
using any one of the modes described in the following table.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Steps for Writing Data into a File in Python
To write into a file, Please follow these steps:
1)Find the path of a file
We can read a file using both relative path and absolute path.
The path is the location of the file on the disk.
An absolute path contains the complete directory list required to
locate the file.
A relative path contains the current directory and then the file
name.
2)Open file in write mode
Pass file path and access mode w to the open() function. The
access mode opens a file in write mode.
For example, fp= open(r'File_Path', 'w')
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
3)Write content into the file
Once a file is opened in the write mode, write text or content into the file
using the write() method.
For example, fp.write('new text').
The write() method will add new text at the beginning of a file. For an
existing file, this new content will replace the existing content. If the file is
not already present a new file will be created, and content is written into it.
4)Close file after completing the write operation
We need to make sure that the file will be closed properly after completing
the file operation. Use fp.close() to close a file.
5)Append content at the end of the file
Pass file path and access mode a to the open() function to open a file in
append mode.
For example, fp= open(r'File_Path', 'a')
Next, use the write() method to write content at the end of the file without
deleting the existing content
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
5)Append content at the end of the file
Pass file path and access mode a to the open() function to
open a file in append mode.
For example, fp= open(r'File_Path', 'a')
Next, use the write() method to write content at the end of
the file without deleting the existing content
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Writing To An Existing File
In an already existing file, while opening the file in the
write mode, the existing content will be overwritten. The
filehandle will be placed at the beginning of the file.
In the below example, we are reading a file to view the old
contents. Next, we are opening a file in the write mode to
write the new content. We can see that the existing content
has been overwritten with the new content.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
File Write Methods
Python provides two different methods to write into a file.
We don’t have to import any module for that.. Below are
the methods.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
writelines(): Write a list of lines to a file
We can write multiple lines at once using the writelines()
method. We can pass a list of strings that we want to add to
the file to it. Use this method when you wanted to write a
list into a file.
The above syntax explains that the list of strings will be
added to the file accessed with the file_obj.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
with Statement to Write a File
We can open a file by using the with statement along with open()
function. The general syntax is as follows.
The following are the main advantages of opening a file using
‘with’ statement
The with statement simplifies exception handling by
encapsulating common preparation and cleanup tasks.
This also ensures that a file is automatically closed after leaving
the block.
As the file is closed automatically it ensures that all the resources
that are tied up with the file are released.
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Appending New Content to an Existing File
With the access mode set to a, the open function will place
filehandle at the end of the file, and then we can add new
text at the end of the existing file using the write() and
writelines() functions.
Now let us add some content to the already created
‘Write_demo.txt’ .
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer
Python –File Handling
Srinivas Rao Aitha - Python Full Stack
Trainer