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. Required fields are marked *

You May Also Like

Programming

This article is prepared to explain concepts that will be important for programming beginners such as data types, variables, heap and stack, and operators....

Programming

This article was created for those who want to use functional programming in their career or who are learning new programming paradigms. We will...

Programming

Functions are pieces of code that combine the integrity of the code used to perform a task into a single structure. If you are...

Programming

Computers can solve an event in different ways, we call these ways algorithms, each algorithm works differently from the others and has different processing...