Computer Science
Write a method in Python to write multiple line of text contents into a text file mylife.txt.line.
Python File Handling
4 Likes
Answer
def write_to_file(file_path):
lines_to_write = ["The sun sets over the horizon.", "Birds chirp in the morning.", "Raindrops patter on the roof.", "Leaves rustle in the breeze."]
with open(file_path, "w") as file:
for line in lines_to_write:
file.write(line + '\n')
write_to_file("mylife.txt.line")
Answered By
3 Likes
Related Questions
Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is the following code fragment doing ?
f = open("poemBTH.txt", "r") nl = 0 for line in f: nl += 1 print(nl)
Write a method in Python to read the content from a text file diary.txt line by line and display the same on screen.
What will be the output of the following code ?
import pickle ID = {1:"Ziva", 2:"53050", 3:"IT", 4:"38", 5:"Dunzo"} fin = open("Emp.pkl","wb") pickle.dump(ID, fin) fin.close() fout = open("Emp.pkl",'rb') ID = pickle.load(fout) print(ID[5])
What will be the output of the following code ?
import pickle List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]] List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]] with open('data.pkl', 'wb') as f: f.write(List1) with open('data.pkl', 'wb') as f: f.write(List2) with open('data.pkl', 'rb') as f: List1 = pickle.load(f) print(List1)