Aim: Program
Aim: Program
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.