Working with Files

♤Write Method

Today,we are going to see how to write in python file. Write in file uses “w”. Syntax of write method. file.write(),write take one display statement.

■■greeting.py

"Hello, world!"
________________________


So,question is how we will do it ?

1.Open the file.
2.Read the file.
3.Close the file.
4.Open the file in write
Mode.
5.use write method.
6.Inside write method,
Whatever content we
want to write.
________________________
________________________
Note: Write method
Overwrite the
file. The old content will erased.
________________________
________________________

■■display.py

f = open("greeting.py",
"r")

with open("greeting.py")
as f:
print(f.read())
f.close()


f = open("greeting.py",
"w")
with open("greeting.py")
as f:
print(f.write("Good
","morning")


Output:

Good,morning

♧append method :

Append method in a file add content to file. Open the file in append mode.

■■Hello.py

"Hello,world ! "

■■go.py
# open the file in
# append mode.

f = open("Hello.py","a")
f.append(" Bob and Alice.")

print(f)

Output :

Hello,world Bob and Alice.

________________________

Note: Append method add
the content in existing file content.
________________________

♤♧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