Computer Science
Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents. What will be the difference if the file was opened in write mode instead of append mode?
Python File Handling
5 Likes
Answer
f = open("hello.txt", "r")
st = " "
while st:
st = f.readlines()
print(st)
f.close()
If the file "hello.txt" was opened in write mode instead of append mode, it would have overwritten the existing content of the file. In write mode ("w"), opening the file truncates its content if it already exists and starts writing from the beginning. Therefore, the previous contents of the file would have been replaced with the new lines provided in the write mode code snippet.
Answered By
3 Likes
Related Questions
What is the difference between the following set of statements (a) and (b):
(a)
P = open("practice.txt", "r") P.read(10)
(b)
with open("practice.txt", "r") as P: x = P.read()
Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode.
“ Welcome my class” “It is a fun place” “You will learn and play”
Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.
Define pickling in Python. Explain serialization and deserialization of Python object.