Connect with us

Hi, what are you looking for?

File Handling In Python
File Handling In Python

Programming

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:
   print(a)

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:
   print(a)

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.

CONGRATULATIONS, YOU FINISHED FILE HANDLING IN PYTHON!

Click to comment

Leave a Reply

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

You May Also Like

Programming

clean code is essential for updating scripts, adding new features to code, etc. So every developer, must learn how to clean the code. With...

Daily News

Cloud computing is a system that is often heard today and that most developers use at least once. In this article, we’ll look at...

Game Development

Visual Studio Code without a doubt, most popular and loved code editor in the code editor market. Many developers love working with Vs Code....

Artificial Intelligence

GitHub Copilot was introduced last year and continues to make it easier for developers with nice updates to date. Although most people see Github...