Skip to main content

File Handling in Python

In our previous Python tutorial, you have learned how to Import CSV File into MongoDB using Python. In this tutorial, you will learn about File handling in Python.

The files are widely used in to store data permanently in web application. Python provides us with an important feature for reading data from the file and writing data into a file. It has built-in function read() and write() to perform operations with files.

So let’s proceed with file handling in Python.

File Handling in Python

While developing applications, when there are large data and it needs to save or store somewhere. Files are the best choice to store data permanently for further use. The files data can be read, update and delete. The popular file types (text, CSV, Excel, JSON) are used to store data.

There are built-in functions in Python for reading, writing and deleting files. The open() function is used to open files for reading and writing files. The function open() takes two parameters; filename, and mode (‘r’, ‘w’, ‘a’, ‘x’) for reading, writing, appending and creating files.

Opening a file in Python

We need to open file to perform any operation on file. We need to use built-in open() function to open file. The file can be opened for different purpose like read, write, append etc. So we need to specify the mode to open file.

file = open(filename, mode)

Supported file open mode:

  • r: Open file for a read operation.
  • w: Open an existing file for write operation. If file is not exist then file will be created.
  • a: Open an existing file for append operation.
  • r+: Open to read and write operation.
  • w+: Open to read and write operation.
  • a+: Open to read and append data.

Creating a File in Python

We can use open() function with file name and mode x to create a new file. The file will be created if file is not exist otherwise error returned.

file = open("employee.txt", "x")

The above will create a employee.txt file. Also when we open a file with mode append a or write w then the file will be created if file not exist.

Writing a File in Python

We can write content to file using write() function. The write() function overwrite the file content. We need to open file with write mode w to write to file.

file = open("employee.txt", "w")
file.write("Content to write into employee.txt file.")
file.close()

above code will open file employee.txt in write mode and write content to file using write() function.

We can also append content to a file by opening file in append a mode.

file = open("employee.txt", "a")
file.write("Content to append into employee.txt file.")
file.close()

Above code will append content to employee.txt file as the file opened in append a mode.

Reading file in Python

We can read the file content by opening file r read mode. We need to use read() function to read the content of file after opening in read mode.

file = open("employee.txt", "r")
print(file.read())
file.close()

The above code will open the file in read r mode and then read file content using read() function. The content printed using print() function.

We can also read whole file, line by line. We need to read the file and looping through the lines of the file. Here is code to read file line by line.

file = open("employee.txt", "r")
for x in file:
  print(x)
file.close()

Closing a file in Python

It is always a good practice to close the file when you are done with it. You can use close() function to close the file like below.

file = open("employee.txt", "r")
print(file.read())
file.close()

In above code, we are closing file using file.close() after file reading is done.

Deleting a file in Python

We can delete the file using Python. We need to import the OS module to use remove() function to delete the file.

import os
if os.path.exists("employee.txt"):
  os.remove("employee.txt")
else:
  print("The file does not exist")

The above code will import OS module and check if file employee.txt exist to delete the file. If the file is exist then delete using remove() function otherwise display message that the file does not exist.