Experiment: 03
Aim : Operations on file in python.
Theory:
In Python, there are several operations that can be performed on files. Some of the
common file operations in Python are:
Opening a file
Reading a file
Writing to a file
Appending to a file
Closing a file
Renaming a file
Deleting a file
Program:
Aim : Opening a file in write mode
file = open("example.txt", "w")
Aim : Writing to a file
file.write("Hello, World!")
file.write("\nThis is an example file.")
Aim : Closing a file
file.close()
Aim : Opening a file in read mode
file = open("example.txt", "r")
Aim : Reading a file
print(file.read())
Aim : Closing a file
file.close()
Aim : Opening a file in append mode
file = open("example.txt", "a")
Aim : Appending to a file
file.write("\nThis is an appended line.")
Aim : Closing a file
file.close()
Aim : Renaming a file
import os
os.rename("example.txt", "new_example.txt")
Aim : Deleting a file
os.remove("new_example.txt")
Output:
Conclusion: We have Performed Operations on file in Python