def write_to_file(filename, data):
"""
Write data to a file.
Parameters:
filename (str): The name of the file to write to.
data (str): The data to write into the file.
"""
with open(filename, 'w') as file:
file.write(data)
print(f"Data written to file '{filename}' successfully.")
def read_from_file(filename):
"""
Read data from a file.
Parameters:
filename (str): The name of the file to read from.
Returns:
str: The data read from the file.
"""
with open(filename, 'r') as file:
data = file.read()
print(f"Data read from file '{filename}':")
return data
if __name__ == '__main__':
filename = input("Enter the name of the file: ")
# User choice for operation
print("\nChoose an operation:")
print("1. Write to the file")
print("2. Read from the file")
choice = input("Enter your choice (1/2): ")
if choice == '1':
# Writing to the file
data_to_write = input("Enter the data to write into the file: ")
write_to_file(filename, data_to_write)
elif choice == '2':
# Reading from the file
data = read_from_file(filename)
print(data)
else:
print("Invalid choice. Please enter 1 or 2.")
Output :
Enter the name of the file: test
Choose an operation:
1. Write to the file
2. Read from the file
Enter your choice (1/2): 1
Enter the data to write into the file: Good Morning. Welcome to Vidya Vikas
Data written to file 'test' successfully.
Enter the name of the file: test
Choose an operation:
1. Write to the file
2. Read from the file
Enter your choice (1/2): 2
Data read from file 'test':
Good Morning. Welcome to Vidya Vikas
Explanation :
In this program, two functions are defined:
write_to_file
:- Takes a filename and data as input.
- Opens the file in write mode (
'w'
), which either creates the file if it doesn't exist or truncates the file if it already exists. - Writes the data to the file.
- Closes the file automatically when the
with
block exits.
read_from_file
:- Takes a filename as input.
- Opens the file in read mode (
'r'
). - Reads the data from the file.
- Closes the file automatically when the
with
block exits. - Returns the data read from the file.
In the example usage section of the program:
- The user is prompted to enter the filename.
- The user chooses to either write to the file or read from it.
- Depending on the user's choice:
- For the write operation, the program prompts the user to enter the data to write to the file and then calls the
write_to_file
function. - For the read operation, the program calls the
read_from_file
function and prints the data read from the file.
- For the write operation, the program prompts the user to enter the data to write to the file and then calls the
No comments:
Post a Comment