Python File Handing


Introduction to File Handling

A file in a computer is a resource for storing different types of data, for example, audio, video, text, etc. Python has support for all the major file handling functionalities like opening, reading, creating and deleting files.

File Paths

A file path is the location in the computer where the file is stored. There are two types of paths we deal with.

1. Absolute Path : The path that contains the complete directory structure to reach the file. It always begins with the root folder.

2. Relative Path : Relative path is the path relative to the current working directory. We can say that relative path is the path of the current working directory. Here, we just specify the file name, and do not include the folder structure in the path.

Basic File Operations

Opening a file

Python has provided us with the open() function to open a file. The Open function needs a file name as the mandatory argument. We can pass mode also, the default mode is ‘r’ which stands for the read. We can override this mode by passing it as an argument.

Following are the few modes that python support:

ModeMeaning
rread
wwrite
aappend
xcreate
In [1]:
file = open('myfile.txt','w')
In [2]:
file
Out[2]:
<_io.TextIOWrapper name='myfile.txt' mode='w' encoding='cp1252'>

Writing a file

To write data to the file, we can simply use the write “w” mode. First, we will open the file using the “w” mode. If the file exists, it will write in the existing file and if it does not exist then it will create the new file. Once the file is opened we have to use the write function to write to the file and then close the file. We will be able to see the file with content in the current folder.

In [1]:
file = open('myfile.txt','w')
In [2]:
file.write("I am learing Python.")
Out[2]:
20
In [3]:
file.close()

Reading a file

To read the content from the file we can use the “r” mode. It will open the file if it already exists and will throw an error if the file does not exist.

In [1]:
file = open("myfile.txt",'r')
In [2]:
file.read()
Out[2]:
'I am learing Python.'
In [3]:
file.close()

Deleting a file

We can also delete the file using the os module. os.remove() function is used to delete the file.

In [1]:
import os
In [2]:
os.remove("myfile.txt")