Back

More on reading from a text file

Q1. Write a program to print out all of a text file. Test it works on a text file you have saved.
Q2. Type this program into Python (or modify your own) and test it. What does it do?

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

Q3. Modify the above program to print out the first 20 characters.
Q4. Modify the above program so it prints 20 characters from the tenth character.
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()

Describe what the above program is doing.
Q6. Instead of creating the list from the start of the poem, modify the code above so that it starts from character 21.
Q7. Print out the poem one line at a time using a for loop using a standard for loop construction. If you can't work out how to do it, use the Internet for research! If you know how to use for loops, have a go!
Q8. Print out the first 5 characters from one of your own poems.
Q9. Print out the first 5 characters from one of your own poems starting at character 10.
Q10. Print out the lines from one of your own poems as a list. Then use a for loop to print out your poem line by line.

Back