Nov 04: Reading and Writing Files
Learning Objectives
After today's class, you should be able to:
- Create a new text file, and output several lines to the file.
- Open an existing file, and append several lines to the file.
- Read a text file line by line, and extract data from the file.
Reminders¶
- Due TODAY: Part A Canvas Quiz
- Due Tuesday: Chapter 10: File I/O
- Due Thursday: Part B Gradescope
PA1 Debrief¶
- game_logic.py
- test_game_logic.py
POGIL Activity¶
- FileIO.pdf
- If you are absent today, complete this activity at home
- Bring your completed activity to class or office hours
Model 1¶
write.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 |
|
Model 2¶
afile.write("new line\n")
afile = open("out.txt", "a")
afile.write("new line\n")
afile.write(2.0)
afile.write("2.0")
afile.close()
afile.write("new line\n")
After running the above code, the file contents should be:
out.txt | |
---|---|
1 2 3 4 5 6 |
|
Model 3¶
infile = open("out.txt", "r")
infile.readline()
infile.readline()
infile.readlines()
infile.readline()
infile.close()
infile = open("out.txt", "r")
for line in infile:
print(line)
infile.close()
infile = open("out.txt", "r")
for i in range(3):
infile.readline()
line = infile.readline()
infile.close()
line
line[0]
line[0:5]
words = line.split()
words
words[0]
The following file can be used for the last question: