Python Saving What You Fetch
Saving what you fetch means writing fetched text into a file. The file keeps the words after the program ends.
Fetch the text to save
urlopen() fetches the words from a data address. decode() turns them into plain text.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20river%20runs%20to%20the%20sea.')
text = reply.read().decode()
print(text)Write the text to a file
open() with "w" makes a file for writing. write() puts the fetched text inside it.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20river%20runs%20to%20the%20sea.')
text = reply.read().decode()
with open("saved.txt", "w") as f:
f.write(text)
print("Saved:", len(text), "characters")Read the saved file back
The second open() reads the file the first one wrote. The saved words print out again.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20river%20runs%20to%20the%20sea.')
text = reply.read().decode()
with open("saved.txt", "w") as f:
f.write(text)
with open("saved.txt") as f:
print(f.read())Example
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20river%20runs%20to%20the%20sea.')
text = reply.read().decode()
with open("fetched.txt", "w") as f:
f.write(text)
with open("fetched.txt") as f:
saved = f.read()
print(saved)
print("Characters:", len(saved))Key points
- Use open(name, "w") to open a file for writing
- Use write(text) to put fetched text into the file
- A with block closes the file when the writing ends
- Use open(name) to open the file for reading
- Use read() on a file to bring back its whole text
- The saved file holds the same words the fetch brought back
In this example, urlopen() fetches one sentence from a data address. read() brings the sentence back as bytes. decode() changes those bytes into text the program can write. open() with "w" writes the sentence into fetched.txt. open() without a mode reads the file back. The printouts show the saved sentence and its length, 26.
Note
A saved file stays on the computer, so the program can read it again later without fetching again.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which open() call opens a file for writing?