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

Leave a comment