Back

More on reading from a text file - Answers

Q1. To write a program to print out all of a text file, do this:

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.read())
poem.close()

Q2. This code prints the first 10 characters in the haiku.

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.read(10))
poem.close()

Q3. To modify the above program to print out the first 20 characters, do this:

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.read(20))
poem.close()

Q4. To modify the above program so it prints 20 characters from the tenth character, do this:

poem = open('haiku.txt','r',encoding='utf-8')
poem.seek(9,0)
print(poem.read(20))
poem.close()

Q5. Another method you can use is readlines(). This returns the file as a list. Each line in the text file is an item in the list. A blank line is represented as the newline escape sequence \n. Type this code in and get it working:

# A program to demonstrate reading and writing
# from and to files.

poem = open('haiku.txt','r',encoding='utf-8')
poem.seek(9,0)
print(poem.read(20))

poem.seek(0)
myList = poem.readlines()
print(myList)

poem.close()

The above program prints out 20 characters from the tenth one, and then saves each line in the poem as an element in a list. It then prints out the list.
Q6. To modify the code above so that it starts from character 21, do this:

# A program to demonstrate reading and writing
# from and to files.

poem = open('haiku.txt','r',encoding='utf-8')
poem.seek(9,0)
print(poem.read(20))

poem.seek(20,0)
myList = poem.readlines()
print(myList)

poem.close()

Q7. To print out the poem one line at a time using a for loop, do this:

# A program to demonstrate reading and writing
# from and to files.

poem = open('haiku.txt','r',encoding='utf-8')
poem.seek(9,0)
print(poem.read(20))

poem.seek(21)
myList = poem.readlines(0)
print(myList)

poem.seek(0)

for a_line in poem:
    print(a_line, end=' ')  #The end=' ' will stop double line spacing happening

poem.close()

Q8 - Q10 is practising the above skills with their own text files.

Back