For any queries you can reach us at / WhatsApp us: +919158876092

Python File Handling


Python File Handling

File handling is a important component of any application.

Python has multiple functions for creating, reading, updating, and deleting files. In Python, the open() function is used to working with files.

The open() function takes two parameters; filename, and mode.

In mode, we specify whether we want to read r, write w or append a to the file. We can also define if we want to open the file in text mode or binary mode.

In Python, file handling operation occurs in the following order:

  1. Open a file using open() function.
  2. Perform the operation (read or write).
  3. Close the file using close() function.

There are different methods (modes) for opening a file:

Mode Name Description
r Read Opens a file for reading, returns an error if the file does not exist. It is a default mode.
w Write Opens a file for writing a file, creates the file if it does not exist or deletes the content of the file if it exists.
a Append Opens a file for appending at the end of the file without deleting the content of it, creates the file if it does not exist
x Create Creates the specified file, returns an error if the file exists
t Text mode Opens a file in text mode. It is a default mode.
b Binary mode Opens a file in binary mode.
+ Update Opens a file for updating i.e. reading and writing.


For reading a file it enough to specify the name of the file.

f = open("file_name.txt")               # open a file in current directory
f = open("C:/Python/file_name.txt")     # define full path

f = open("file_name.txt")               # identical to 'r' or 'rt'
f = open("file_name.txt",'w')           # write in text mode
f = open("image_file.bmp",'r+b')        # read and write in binary mode

The best way to close a file is by using the with statement. This ensures that the file is closed when it exit and it avoids the runtime exception.

Reading Files in Python

In order to read a file in Python, we must open the file in reading r mode.

Following methods are useful while reading a file:

Method Description
read(size) Read data from specified size i.e. number of lines. If the size parameter is not specified, it reads the entire file.
>>>    # read the first 4 data
seek() We can change the file cursor (position) using seek() method.
>>> f.tell()    # returns the current file position
tell()() tell() method returns the current position of cursor.
>>>   # set file cursor to initial position

Read one line of the file:

f = open("test.txt")

Read all lines of the file:

with open("test.txt", 'rt') as f:

Writing to Files in Python

In order to write a file in Python, we need to open it in write w, append a or creation x mode.

We need to be concerned with the write w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are deleted.

Open the file "test.txt" and append content to the file:

f = open("test.txt", 'a')    
f.write("Hello world!")

Open the file "text.txt" using with statement:

with open("test.txt, 'w') as f:
   f.write("my first line\n")
   f.write("this is second line\n\n")
   f.write("this is third line\n")

In above example, write w mode will overwrite the contents of text.txt file.

Deleting files in Python

In order to delete a file, you must import the OS module, and run its os.remove() method:


import os

if os.path.exists("text.txt"):
    print("The file does not exists")

In above example, os.path.exists() method is used to check whether file exists or not. If exists it will remove using os.remove() method. Otherwise it will return fle does not exists.