In: Computer Science
Using python
Write a program that has 3 functions, named write_to_file, read_from_file, and ask_user.
The write_to_file function should have 2 parameters, file_name and data. When called, the function will open a file with the name stored in the file_name variable, write the information stored in data, then close the file.
The read_from_file function will have 1 parameter, file_name. When called, the function will open a file with the name stored in the file_name variable, print the contents of the file, then close the file.
The ask_user function will give the user a prompt asking whether they want to read or write a file, once a selection is made the program must ask the user for the information needed to run the function (if they select write, ask for file name and data to write to the file, if the select read, ask for file name).
Below the functions, in the main part of the program, write a for loop that loops 10 times calling the ask_user function.
def write_to_file(name,data):
#opening the file and wrtiing into it
file = open(name,"w")
file.write(data)
file.close()
def read_from(name):
#opening file to read data
file = open(name)
#reading line by line
for x in file:
print(x)
file.close()
def ask_user():
#asking the user to choose
ch=int(input(("Please choose\n1 Write to File\n2 Read from file\n")))
#reading user input according to choice
if ch==1:
name=input("Enter file name: ")
data=input("Enter data to write")
write_to_file(name,data)
elif ch==2:
name=input("Enter file name: ")
read_from(name)
for i in range(10):
ask_user()
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
Please Like and Support me as it helps me a lot