7.1 File I/O
Files store data persistently. Variables in memory disappear when a program ends, but data written to a file can remain. File I/O means input from files and output to files.
open()
Open a file before operating on it. open() returns a file object, and later reading, writing, and closing happen through that object.
python
file = open("text.txt", "r", encoding="UTF-8")
content = file.read()
file.close()Common file modes:
r: read only; the file must exist.w: write only; creates a new file and overwrites existing content.a: append; writes new content at the end.r+: read and write; the file must exist.
Prefer with open(...) as file because the with statement closes the file automatically when the block ends.
python
with open("text.txt", "r", encoding="UTF-8") as file:
content = file.read()Note
When reading text files, it is usually better to write
encoding="UTF-8". If you omit encoding, different systems may use different defaults.Loading concept check...
Read Methods
Common file reading methods:
read(): read the entire file and return a string.readline(): read one line and return a string.readlines(): read all lines and return a list of strings.
Loading interactive lab...
Loading concept check...
Loading practice...
Parsing Words
The program below reads quotes.txt, removes punctuation, and writes each word into words.txt. In this example, quotes.txt contains:
text
Talk is cheap. Show me the code.
Code never lies, comments sometimes do.
Stay Hungry Stay Foolish.python
import string
with open("words.txt", "w", encoding="UTF-8") as output_file:
with open("quotes.txt", "r", encoding="UTF-8") as input_file:
for line in input_file:
words = line.split()
for word in words:
word = word.strip(string.punctuation)
output_file.write(word + "\n")with blocks can be nested. The outer block opens the output file, and the inner block reads the input file.
After the program runs, words.txt becomes:
text
Talk
is
cheap
Show
me
the
code
Code
never
lies
comments
sometimes
do
Stay
Hungry
Stay
FoolishLoading concept check...
Loading practice...