Connect with us

Hi, what are you looking for?

File Handling In Python
File Handling In Python


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.


Click to comment

Leave a Reply

Your email address will not be published.

You May Also Like

Game Development

In this article, we will generate a movement script for FPS games in Unity. We’ll cover all the mechanics like camera control, crouching, and...

Game Development

In this article, we are going to look at how to use SQLite RDBMS in Unity 3D. After this article, you’ll be able to...

Machine Learning

In this article, we are going to learn how to build regression models with PyCaret in Python. If you don’t have any experience with...


In this article, we will make a simple login system in SwiftUI. After this article, you will be able to make a custom login...