Writing to a text file - Answers
Q1. Type this code into Python and get it working:
# A program to demonstrate reading and writing
# from and to files.
with open('haiku2.txt','w',encoding='utf-8') as newPoem:
newPoem.write('the first cold shower\neven the monkey seems to want \na little coat of straw.')
with open('haiku2.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())
This code opens up a new file object in write access mode. It then writes three lines to the file and closes it. It then opens up the file and prints out the lines.
Q2. To create then print out yet another haiku:
with open('haiku2.txt','w',encoding='utf-8') as newPoem:
newPoem.write('the first cold shower\neven the monkey seems to want \na little coat of straw.')
with open('haiku2.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())
print('\n')
with open('haiku3.txt','w',encoding='utf-8') as newPoem:
newPoem.write('On the jagged cliff\nsadly gazing far below\nhis troubles end here.')
with open('haiku3.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())
Q3. If you try to a file that already has something in it, you will overwrite the contents.
Q4. If you open up an existing file with the append access mode, you will add the strings to the end of the file.
Q5. Write some extra code that appends a line space followed by the name of the poet and his birth and death dates on a new line.
# A program to demonstrate reading and writing
# from and to files.
with open('haiku2.txt','w',encoding='utf-8') as newPoem:
newPoem.write('the first cold shower\neven the monkey seems to want \na little coat of straw.')
with open('haiku2.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())
print('\n')
with open('haiku3.txt','w',encoding='utf-8') as newPoem:
newPoem.write('On the jagged cliff\nsadly gazing far below\nhis troubles end here.')
with open('haiku3.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())
print('\n')
with open('haiku3.txt','a',encoding='utf-8') as newPoem:
newPoem.write('\n\nMatsuo Basho 1644 - 1694!')
with open('haiku3.txt','r',encoding='utf-8') as newPoem:
print(newPoem.read())