Python File I/O

A file in Python is a named location which is used to store data in a non-volatile memory (e.g. hard disk). The main memory (i.e. RAM) is volatile in nature and loses its data when computer is turned off. That’s why file is needed for future use of the data.

When we want to read from or write to a file we need to open it first. And when our work completes, it needs to be closed, so that resources that are associated with the file are released.

In Python, the file operation may take place in the following sequence:

  1. Open a file
  2. Perform read or write operation
  3. Close the file

 

1) Opening a File

We use the open () method to open a file in read or write mode. Basically, open ( ) will return a file object. To return a file object we use open() method along with two arguments, that accepts file name and the mode, whether to read or write. So, the syntax being: 

open(filename, mode)

There are several types of mode, that Python provides and how files can be opened:

  • r“,  to open a file for reading.
  • w“,  to open a file for writing.
  • x“,  to open a file for exclusive creation.
  • a“,  to open a file for appending.
  • t“,  to open a file in text mode (default).
  • b“,  to open a file in binary mode.
  • r+“, to open a file for both reading and writing

We should keep in mind that the mode argument is not mandatory. If not passed, then Python will assume it to be “r” by default.

 

2) File Handling for Reading

Let’s look at the simple program to open a file named “sample.txt” (stored in the same directory) in “r” mode and printing its content on the console using the read() method:

# Opens a text file in read mode 
try:
file = open("sample.txt", "r")
print(file.read())

except:
print("File error")

finally:
file.close() # Closes the file

Output:

Hi! Welcome to "sample.txt" file.
It is for testing purposes only.
Happy Learning!

 

3) File Handling for Writing

To write to an existing file, we have to use a parameter to the open() function apart from the file name itself:

  • w“,  to open a file for writing.
  • x“,  to open a file for exclusive creation.
  • a“,  to open a file for appending.

Let’s look at another program to write to a file named “myfile.txt” opened in “w” mode (create a new file if it does not exist). We will use the write() method here. See below: 

# Python code to create a file for writing
try:
file = open('myfile.txt','w')
file.write("This is the write command. ")
file.write("It allows us to write in a particular file.")

except:
print("File error")

else:
print("Written successfully.")

finally:
file.close() # Closes the file

Output:

Written successfully.

 

4) Delete file or directory

Python allows us to delete an existing file or directory. To delete a file we must import the os module, and run its remove() method. For removing a directory, we need to use the rmdir() method of the os module.

To prevent errors, we may want to check if the file or directory exists before deleting it.

The following program performs the deletion operation on file or directory:

import os
# to check if the file exists
if os.path.exists("myfile.txt"):
os.remove("myfile.txt") # removes a file
else:
print("The file does not exist")

# to check if the directory exists
if os.path.exists("mydir"):
os.rmdir("mydir") # removes a directory
else:
print("The directory does not exist")