Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Python File I/O

Python file handling operations also known as Python I/O deals with two types of files. They are:

  • Text Files
  • Binary

Even though the two file types may look the same on the surface they encode data differently.
A text file is structured as a sequence of lines. And each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted as End of Line, also known as EOL. There are a few special characters that are used as EOL,  but is the comma {,} and newlines are the most common ones.
Image files such as .jpg, .png, .gif, documents such as .doc, .xls, .pdf all of them are nothing but binary files.
Now that we have got an idea of what text and binary files are, we are ready to dive into the discussion of different file handling methods. Following is the list of all the topics that we will cover in this module, in case you need to jump to a specific one.

So, without any further delay, Let’s get started.
Watch this Python File Handling video.

Opening a file

To open file in Python the built-in function open() is used. It returns an object of the file which is used along with other functions.
Syntax of Python Open Function:

obj=open(file_name , access_mode, buffer)

• file_name refers to the file which you want to open.
• access_mode specifies the mode in which the file has to be open. It can be “r”, which is used for opening a file only to read file in Python, or “w” used for opening a file only to write to file Python, similarly “a” opens a file in Python in order to append, etc. For more access modes refer to the below given list.
• buffer represents that buffering is performed or not, if buffer value is 0 then no buffering is performed and when buffer value is 1 then line buffering is performed while accessing the file.
Some of the most common access modes are listed below:

rOpens a file only for reading
rbOpens a file only for reading but in binary format.
wOpens a file only for writing. Overwrites the file if the file exists.
wbOpens a file for writing only in binary format.
aOpens a file for appending. It does not overwrite the file just add the data in the file and if file is not created then it creates new file
abOpens a file for appending in binary format.

Example of Python read files line by line with Python open function and Python readlines
Let’s look at the example of Python read files line by line with Python open function and Python readlines. This is how demofile.txt looks like:

This is just a text file
But this is a newline

This is our code:

f= open(‘demofile.txt’, ‘r’)

With the help of open function of Python read text file, save it in a file object and reading lines with the help of readline function. Remember that f.readline() reads a single line from the file object. Also, this function leaves a newline character (\n) at the end of the string.

‘This is just a text file,\n’

Learn Python in 16 hrs from experts

Writing into the file

write() method is used to write a string into the file.
Syntax of Python write function



i.write(“Hello Intellipaat”)

Here, we are opening the demotext.txt file into a file object called i. Now we can use the write function in order to write something to the file.

Wish to Learn Python? Click Here

Reading from the file

read() method is used to read data from the File.
Syntax of Python write function




Hello Intellipaat


Closing a File

It is used to close a file. For this purpose, close() function is used.
Syntax of Python write function





Hello Intellipaat
Become Python Certified in 16 hrs.

Methods in File Handling

There are different methods are used which are as follows:
1. rename() : This is used to rename a file.

import os
os.rename(existing file_name, new file_name)

2. remove(): This method is used to delete a file in Python.

import os

3. chdir(): This method is used to change the current directory.

import os
os.chdir(“new directory path”)

4. mkdir(): This method is used to create a directory.

import os
os.mkdir(“new directory path “)

5. rmdir(): This method is used to remove the directory.

import os
os.rmdir(“new directory path”)

6. getcwd(): This method is used to show the current working directory.

import os

Other file methods:
Method Description

close()To close an open file. It has no effect if the file is already closed.
flush()To flush the write buffer of the file stream.
read(n)To read at most n characters form the file. Remember that it reads till end of file if it is negative or None.
readline(n=-1)To read and return one line from the file.
Remember that it reads at most n bytes, if specified.
readlines(n=-1)To read and return a list of lines from the file.
Remember that it reads at most n bytes/characters if specified.
seek(offset,from=SEEK_SET)It changes the file position to offset bytes, in reference to from (start, current, end).
tell()It returns the current file location.
writable()It returns True if the file stream can be written to.
write(s)To write string s to the file and return the number of characters written.
writelines(lines)To write a list of lines to the file.

That is how we deal with files in Python. Here, we have also discussed different file methods which will be helpful while working on real-world projects.
So far, we have discussed the basics of Python, which are the building blocks to write a python program. Now let us go ahead and discuss how to make our program more robust and secure from potential failures. Click on the next tutorial to find more.

Previous Next

Download Interview Questions asked by top MNCs in 2018?

"0 Responses on Python File Handling"

    Leave a Message

    100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

    Sales Offer

    Sign Up or Login to view the Free Python File Handling.