You are on page 1of 9

File handling in Python

File
• File is a named location on disk to store related information
• It is used to permanently store data in no-volatile memory
• In Python, a file operation take place in the following order
1. Open a file
2. Read or write (perform operation)
3. Close the file
Open a file
• We have to open a file using built-in function open()
• This function returns a file object, also called a handle, it is used to
read or modify the file
• We can specify the mode while opening a file.
• r – Read
• w – Write
• a – Append
What does open() function do in Python
• To work with files in Python, you have to open the file first. So, the
open() function does what the name implies – it opens a file for you
so you can work with the file.
• To use the open function, you declare a variable for it first. The open()
function takes up to 3 parameters – the filename, the mode, and the
encoding.
That’s not all.
• That’s not all. The open() function does not close the file, so you also
have to close the file with the close() method.
• So, a proper way to use the open function looks like this:
with statement in Python
• The with statement works with the open() function to open a file.
• So, you can re-write the code we used in the open() function example
like this:

• Unlike open() where you have to close the file with the close() method,
the with statement closes the file for you without you telling it to.
File writing in Python
• Similarly, for writing data to files, we have to use open() with wt mode
• Also, we have to use the write function to write into a file
Reading all lines
• The following
Modes for opening a file
Mode Description
r Reading only
rb Reading only in binary format
r+ Reading and writing
rb+ Reading and writing in binary format
w Writing only
wb Writing only in binary
Overwrites the file if exists. If the file does not exist,
create a new file for writting

You might also like