Back

Writing to a text file

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())

Check that haiku2.txt has been created. Open up haiku2.txt in a text editor and have a look at it. Describe what the code above actually does.
Q2. In the above code, notice how we created a newPoem file object with the w access mode. This created a file object that we could write to. newPoem is the file object we will use but we associated it with haiku.txt by using open. Also notice how the lines have been separated with a \n. When we exited the first with block, a close file was automatically executed. We then opened a new file object with a read access mode, again in a with block. We used the same name for the file object this time, but we could have named the file object anything we liked.

By adding extra code, create then print out yet another haiku.

Q3. What would happen if I tried to write to a file that already has something in it? For example, in the following code, I write to haiku3.txt, and then I write again to haiku3.txt

# 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())

with open('haiku3.txt','w',encoding='utf-8') as newPoem:
    newPoem.write('\nWhat a fab poem!')

with open('haiku3.txt','r',encoding='utf-8') as newPoem:
    print(newPoem.read())

Q4. Change the fourth line from the bottom so the access mode is a (append). It should be changed from this:

with open('haiku3.txt','w',encoding='utf-8') as newPoem:

to this:

with open('haiku3.txt','a',encoding='utf-8') as newPoem:

What was the difference compared to before the change?

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.

Back