Files in Python

A file is a named location on the disk which is used to store the data permanently.

Here are some of the operations which you can perform on files:

open a file

read file

write file

close file

#1) Open a File

Python provides a built-in function called open() to open a file, and this function returns a file object called the handle and it is used to read or modify the file.

Syntax:

file_object = open(filename)

Example:

I have a file called test.txt in my disk and I want to open it. This can be achieved by:

#if the file is in the same directory
f = open(“test.txt”)
#if the file is in a different directory
f = open(“C:/users/Python/test.txt”)

We can even specify the mode while opening the file as if we want to read, write or append etc.

If you don’t specify any mode by default, then it will be in reading mode.

#2) Reading Data from the File

In order to read the file, first, we need to open the file in reading mode.

Example:

f = open(“test.txt”, ‘r’)
#To print the content of the whole file
print(f.read())
#To read only one line
print(f.readline())

Example: 1

Output:

Example: 2

Output:

#3) Writing Data to File

In order to write the data into a file, we need to open the file in write mode.

Example:

f = open(“test.txt”, ‘w’)
f.write(“Hello Python \n”)
#in the above code ‘\n’ is next line which means in the text file it will write Hello Python and point the cursor to the next line
f.write(“Hello World”)

Output:

Now if we open the test.txt file, we can see the content as: Hello Python Hello World

Output:

#4) Close a File

Every time when we open the file, as a good practice we need to ensure to close the file, In python, we can use close() function to close the file.

When we close the file, it will free up the resources that were tied with the file.

Example:

f = open(“test.txt”, ‘r’)
print (f.read())
f.close()

Output:

#5) Create & Delete a File

In python, we can create a new file using the open method.

Example:

f = open(“file.txt”, “w”)
f.close()

Output:

Similarly, we can delete a file using the remove function imported from the os.

Example:

import os
os.remove(“file.txt”)

Output:

In order to avoid the occurrence of an error first, we need to check if the file already exists and then remove the file.

Using python input/output functions, we can get the input from the user during run-time or from external sources like text file etc. Hope you will be clear about Input-Output and Files in Python from this tutorial.

Our upcoming tutorial will explain about the various Types of Oops available in Python!!