Practice: Writing Files
Q1. Write one line
Write the text Hello file to a file named a.txt, then read it back and print it.
Goal: Write with write().
Q2. Write three lines from a list
Write the items red, green and blue to colors.txt, one per line, then print the number of lines.
Goal: Write lines in a loop.
Q3. Squares file
Write the squares of 1 to 5, one per line, to sq.txt. Then read and print them on one line separated by spaces.
Goal: Write numbers with f-strings.
Q4. Use print to write
Use print(..., file=f) to write the words one and two on separate lines of p.txt, then print the file content with end empty.
Goal: Use print with file.
Q5. Overwrite demo
Write old to x.txt, then open it again in write mode and write new. Print the final content.
Goal: Understand truncation.
Q6. Character count returned
Print the value returned by f.write("python").
Goal: Know the return value of write().
Q7. Glued text
What is printed?
with open("g.txt", "w") as f:
f.write("ab")
f.write("cd")
with open("g.txt") as f:
print(f.read())Goal: Understand write().
Q8. Newline characters
What is printed?
with open("g.txt", "w") as f:
f.write("a\nb\n")
with open("g.txt") as f:
print(f.readlines())Goal: Read what you wrote.
Q9. writelines without newlines
What is printed?
with open("g.txt", "w") as f:
f.writelines(["x", "y", "z"])
with open("g.txt") as f:
print(f.read())Goal: Know writelines().
Q10. Second open wins
What is printed?
with open("g.txt", "w") as f:
f.write("first")
with open("g.txt", "w") as f:
pass
with open("g.txt") as f:
print(repr(f.read()))Goal: Understand truncation.
Q11. Print with sep
What is printed?
with open("g.txt", "w") as f:
print(1, 2, 3, sep=",", file=f)
with open("g.txt") as f:
print(f.read().strip())Goal: Use sep with file.
Q12. Exclusive mode
What is printed?
with open("g.txt", "w") as f:
f.write("1")
try:
open("g.txt", "x")
except FileExistsError:
print("exists")Goal: Use mode x.
Q13. Fix the TypeError
This code crashes with TypeError. Fix it so it writes the number 42.
with open("n.txt", "w") as f:
f.write(42)Goal: Convert values before writing.
Q14. Fix the one-line problem
The program should save each name on its own line, but they run together. Fix it.
names = ["Ann", "Bob"]
with open("n.txt", "w") as f:
for n in names:
f.write(n)Goal: Add newline characters.
Q15. Why lost?
A student ran open("report.txt", "w") only to check if the file exists, and the old report was gone. Explain why.
Goal: Know write mode deletes content.
Q16. write versus print
Name two differences between f.write(x) and print(x, file=f).
Goal: Compare write and print.
Q17. Save a shopping list
Save the items milk, eggs and tea to list.txt with numbers like 1. milk, then print the file.
Goal: Build report lines.
Q18. Write a small table
Write the 3 times table (3 x 1 = 3 up to 3 x 3 = 9) to t.txt and print the last line.
Goal: Generate and check file content.