Oct 30: Quiz 4, Reading ad 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.
Announcements¶
Quiz 4¶
- Two portions to the quiz: written and coding
- Log in as
student - Start exam recording
- Log in to Canvas only
- Raise your hand when complete with Canvas written portion
- Open Thonny for coding portion only
- Submit code through Canvas (will go to Gradescope)
- Log out when finished
Review¶
POGIL Activity¶
- FileIO
- 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: