Python File Handling

File handling means interacting with files that are stored on your computer. These interactions could be reading and writing data to those files. Moreover, file handling is a crucial part of any web application.

In this tutorial, we will cover file handling in Python.

In Python , open() function is the basic function for working with files. This function takes two arguments – filename and mode of operation.

There are different modes of opening a file

“r” : It opens the file for reading, and throws an error if the file is not present. It is the default value (That means if you do not specify the mode, it will open the file in reading mode). 

“a” : It opens the file in append mode. To append simply means to add extra data in addition to the earlier data. If the file is not present, it creates the file with the specified name.

“w” : It opens a file for writing, and creates the file if it is not present.

“x” : It is used to create a new file, and it throws an error if the file is not present.

You can also specify whether the file should be handled in text or binary mode.

“t” : For text mode. This is also the default value.

“b” : For binary mode (Example: images)

Syntax of open function

f = open('sample_file.txt')

The above line is equivalent to

f = open('sample_file.txt', 'rt')

Note: If the file does not exist, you will get an error.

Reading a file

When we call the open() function, it returns a file object, which has a method named as read(), that can be used to read the file content.

f = open('sample_file.txt', 'r')
file_content = f.read()
print(file_content)

The above code will work if the text file and the Python file are in the same directory. But, if the sample_file.txt file is located in a different directory, you will need to specify the whole path.

f = open('E:\\mysamplefiles\sample_file.txt', 'r')
file_content = f.read()
print(file_content)

Reading parts of a file

The read method returns the whole text by default, but you can specify how many characters you want to print.

For example, if we want to print first 10 characters, then

f = open('sample_file.txt', 'r')
file_content = f.read(10)
print(file_content)

Reading lines

The readline method can be used to return one line at a time.

f = open('sample_file.txt', 'r')
f.readline()

If you want to print first four lines, you can use the readline method four times.

f = open('sample_file.txt', 'r')
f.readline()
f.readline()
f.readline()
f.readline()

Looping through the lines

You can loop through the lines to read the whole file.

f = open('sample_file.txt', 'r')

for l in f:
    print(l)

Closing files

It is a good practice to close the file when you’re done working with it. For this, you can use the close method.

f = open('sample_file.txt', 'r')
print(f.read())
f.close()

Writing to a file

To write to a file, you need to add another parameter to the open function. Either ‘w’ or ‘a’.

‘a’ : Appends extra content to the previous content.

‘w’ : Writes the new content to the file replacing the older content.

Suppose the sample_file.txt has this content

Hello! How are you?

And we want to add another sentence. Then,

f = open("sample_file.txt", "a")
f.write("What is the plan for today?")
f.close()

And Now if we look at the file, it will have this content

Hello! How are you? What is the plan for today?

The below code will overwrite the content of the file with the new one.

f = open("sample_file.txt", "w")
f.write("This is a test")
f.close()

Now, if we look at the file, it will have following content

This is the test

Creating a new file

For creating a new file, we can use the open method with one of these parameters:

“x” : Create – It will create a new file and return and error if the file exist.

“a” : Append – It will create a file if the specified file does not exist.

“w” : Write – It will create a file if the specified file does not exist.

Example

f = open("newfile.txt", "x")

A new file named newfile.txt would be created.

Deleting a file

Python has a built-in OS module which can be used for deleting files. Before using it, you need to import it in the script.

import os
os.remove("sample_file.txt")

If you want to check if the file exists. Then

import os
If os.path.exists("sample_file.txt"):
    os.remove("sample_file.txt")
else:
    print("This file does not exist")

Check if the directory path exists

import os
dir_path ="E:\\MyFolder\\"

If os.path.exists(dir_path):
    print(f"The directory '{dir_path}' exists.")
else:
    print(f"The directory '{dir_path}' does not exist.")