Practice: Reading Files

« Read the chapter

Q1. Read and print a file

BeginnerCoding

A file notes.txt holds three lines (the setup code below creates it). Write a program that creates it, then reads it and prints the whole content without an extra blank line at the end.

Goal: Read a whole file.

Q2. Count the lines

BeginnerCoding

Create notes.txt with the three fruit lines and print how many lines it has.

Goal: Use readlines().

Q3. Print the first line only

BeginnerCoding

Create notes.txt and print only its first line without the newline.

Goal: Use readline().

Q4. Numbered lines

IntermediateCoding

Create notes.txt and print each line with its number, like 1: apple.

Goal: Loop over a file with enumerate.

Q5. Total characters without newlines

IntermediateCoding

Create notes.txt and print the total number of letters in all lines, not counting newline characters.

Goal: Accumulate values while reading.

Q6. Handle a missing file

IntermediateCoding

Write a program that tries to open ghost.txt and prints Missing if the file does not exist.

Goal: Catch FileNotFoundError.

Q7. What does read() print?

BeginnerOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    print(repr(f.read()))

Goal: Understand newlines in file text.

Q8. Two readline calls

BeginnerOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    a = f.readline()
    b = f.readline()
print(a.strip(), b.strip())

Goal: Understand the file position.

Q9. Read after read

IntermediateOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    f.read()
    print(repr(f.read()))

Goal: Understand the file position.

Q10. Seek back to start

IntermediateOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    f.read()
    f.seek(0)
    print(f.readline().strip())

Goal: Use seek().

Q11. splitlines result

BeginnerOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    print(f.read().splitlines())

Goal: Use splitlines().

Q12. Last line

IntermediateOutput

What is printed?

Code
with open("notes.txt", "w") as f:
    f.write("apple\nbanana\ncherry\n")
with open("notes.txt") as f:
    lines = f.readlines()
print(lines[-1].strip(), len(lines))

Goal: Index into readlines().

Q13. Fix the missing close

BeginnerDebugging

The code below never closes the file safely. Rewrite it with with so the file is closed automatically.

Code
f = open("notes.txt")
text = f.read()
print(text)

Goal: Use with open().

Q14. Fix the comparison

IntermediateDebugging

The program should print Found when apple is in the file, but it prints Not found. Fix it.

Code
with open("notes.txt") as f:
    for line in f:
        if line == "apple":
            print("Found")

Goal: Remove newlines before comparing.

Q15. Why use with?

BeginnerConceptual

Explain in one or two sentences why with open(...) is better than calling open() and close() by hand.

Goal: Explain the with statement.

Q16. read() versus looping

IntermediateConceptual

When should you prefer a for loop over read()?

Goal: Compare reading methods.

Q17. Longest line

IntermediateApplication

Create a file with the lines hi, hello and hey, then print the longest line.

Goal: Process lines from a file.

Q18. Sum numbers from a file

IntermediateApplication

A file holds the numbers 4, 7 and 9, one per line. Create it and print their sum.

Goal: Convert file text to numbers.