File I/O
- Python course
- Intermediate
- Lesson 115/116
- 6 min
Save and load data as JSON.
File I/O: read with with
In this lesson you will read from a file-like object with the with statement. io.StringIO makes a string behave like a file:
from io import StringIO
with StringIO("kiraz") as f:
print(f.read())The starting code includes the previous solutions. You will add from io import StringIO and the with block. StringIO is useful for testing file operations.
This is the skeleton of real file-reading code.
Practice Write a with block with StringIO
Write from io import StringIO. Inside a with StringIO("kiraz") as f: block write print(f.read()).
Starter code
# Word processing - word list
words = ["elma", "armut", "elma"]
print(len(words))
def say(words):
return len(set(words))
print(say(words))
def uret(words):
for w in words:
yield w
for w in uret(words):
print(w)
# write a with block with StringIOSample solution
words = ["elma", "armut", "elma"]
print(len(words))
def say(words):
return len(set(words))
print(say(words))
def uret(words):
for w in words:
yield w
for w in uret(words):
print(w)
from io import StringIO
with StringIO("kiraz") as f:
print(f.read())Expected output
3 2 elma armut elma kiraz
Next step: putting it together
File I/O is ready — you can read from file-like objects with with. In the final lesson you will combine everything into a class: you will define and use a Sayac class. This final layer will make the code modular and reusable.
Classes keep data and methods together; this makes the code organised and testable. All the pieces of the project now come together.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the StringIO import
from io import ____
with StringIO("kiraz") as f:
print(f.read())
from io import StringIO
with StringIO("kiraz") as f:
print(f.read())
Explanation: StringIO comes from the io module.
2 What happens to the StringIO object when the with block ends?
- Stays open
- Is deleted
- Raises an error
- Auto-closes Correct answer
Explanation: When the with block ends the object auto-closes.
3 Match file I/O
| Term | Meaning |
|---|---|
from io import StringIO |
Import |
with StringIO |
Starts the block |
f.read() |
Reads |
with end |
Auto-closes |