File Handling in Python

In this tutorial, we going to look at file handling in Python programming. This tutorial consists of open a file, write the file, and another subject.

Open Function

With the open () function, you can switch your files to writing and reading mode. The open function requires 2 arguments. The first argument is the name of your file and the second argument is the operation you want to do.

open(fileName , Mode)

We have 4 modes, these modes are “r”, “w”, “a”, “r +” r mode is for reading the file, w mode is for writing to the file, a mode is for adding to the file, and r + is for both reading and writing.

File = open("File.txt" , "w+") #Creating File
File = open("File.txt" , "r+") #Reading Mode

When we try to read this file, nothing will be shown on the screen, so let’s add a text to this file and try to read it again. For this, we can use a new method, the write method.

Write Function

Using the write function is easy, you just need to add the text you want as an argument and finish, then we use the for the function to display it.

File = open("File.txt" , "w") #Writing Mode
File.write("This first line")
File = open("File.txt" , "r") #Reading Mode

for a in File:

When we are done with the file, we need to close it using the close function. Let’s read this file again to try this function and then close the file.

Close Function
for a in File:

File.close() #Close the file

Closing the file gives you a lot of advantages, it solves many problems from using a ram to deleting files, remember you cannot delete the file while the file is open.


Leave a Reply

Your email address will not be published. Required fields are marked *