♤♧Working with files in Python ♧♤

Sometime, we have to work the file in python. For this purpose we use different file operations. The File operations are:-

● Read a file(“r”)

● Write a file(“w”)

● Append a file(“a”)

● Create a file(“x”)

The file operation are happening with help of open() function . Open function return a object.

■ Read the file ■

file.py

1)file_o=open("tesla.py","r")

2)with open("tesla.py")
as file_o:
con = file_o.read()
print(con)

This code open the tesla.py file and read the file.
We have to close the file properly. Because, it can lose some data. We use:

3)file_o.close()

Example,

pi_digits.py

3.1434756892380537685783
Open this file and read the content.

file_reader.py

# store the file name
file_o = "pi_digits.py"

with open("pi_digits.py") as
file_o:
con = file_o.read()
print(con)

Output ■■

3.1434756892380537685783

Leave a comment