2. Define a function write_to_file(filename, text) that takes in a filename (a string) and a list of strings as arguments. Your function will open a file and write the contents of text onto the file. Each element in the list represents a separate line in the file, without newline characters. You will have to add the newline characters in yourself. This function does not return or print anything; it will create a new file.
Code Explanation:
Points to remember:
The file will be created in the folder where you save your code
Code:
def write_to_file(filename, text):
f = open(filename,"w")
for i in range(len(text)):
print(text[i], file = f)
f.close()
write_to_file("countries.txt",["USA", "England", "Ireland", "Canada", "Australia"])
Code Screenshot:
O/P:
output will be a file named countries1.txt with each string in the list on a seperate line.
(If you still have any doubts please comment I will definitely help)
Get Answers For Free
Most questions answered within 1 hours.