Connect with us

Hi, what are you looking for?

Programming

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:
   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.

You May Also Like

Cyber Security

TCP/IP is a set of rules that allow computers to communicate with each other on a network such as the Internet. Currently, we do...

News

According to a study from Dartmouth College, Dartmouth’s Tuck School of Business, and Indiana University, artificial intelligence systems can be trained to produce human-like...

Game Development

In this article, we are going to add the double jump feature for a simple 2D platform game. You can implement it in a...

Cyber Security

In this article, we are going to look at XSS attack types and how these attacks harm us. Also, we are going to learn...