0% found this document useful (0 votes)
3 views2 pages

Aim: Program

The document presents a Python program that implements basic file handling operations including writing, reading, appending, and deleting files. It features a menu-driven interface allowing users to choose operations and interact with a sample file named 'sample.txt'. The program handles errors such as file not found and provides user feedback on the success of each operation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Aim: Program

The document presents a Python program that implements basic file handling operations including writing, reading, appending, and deleting files. It features a menu-driven interface allowing users to choose operations and interact with a sample file named 'sample.txt'. The program handles errors such as file not found and provides user feedback on the success of each operation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Aim: Write a Python program to implement ‘File Handling Operations’ in Python.

Program:
import os
def write_to_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
print("Data written successfully!")
def read_from_file(filename):
try:
with open(filename, 'r') as file:
print("File Content:")
print(file.read())
except FileNotFoundError:
print("Error: File not found!")
def append_to_file(filename, content):
with open(filename, 'a') as file:
file.write(content)
print("Data appended successfully!")
def delete_file(filename):
try:
os.remove(filename)
print("File deleted successfully!")
except FileNotFoundError:
print("Error: File not found!")
def main():
while True:
print("\nFile Handling Operations:")
print("1. Write to File")
print("2. Read from File")
print("3. Append to File")
print("4. Delete File")
print("5. Exit")
choice = input("Enter your choice: ")
filename = "sample.txt"
if choice == '1':
content = input("Enter content to write: ")
write_to_file(filename, content)
elif choice == '2':
read_from_file(filename)
elif choice == '3':
content = input("Enter content to append: ")
append_to_file(filename, content)
elif choice == '4':
delete_file(filename)
elif choice == '5':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()

Output:

Output:
Thus, we have successfully implemented a Python program to implement ‘File Handling
Operations’ in Python.

You might also like