Skip to content

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

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
outfile = open("out.txt", "w")
outfile.write("Example ")
outfile.write("output ")
outfile.write("text file\n")
outfile.write("xyz Coordinates\n")
outfile.write("MODEL\n")
outfile.write(f"ATOM {1:3d}")
seq = f"n {0:5.1f}{1:5.1f}{2:5.1f}"
outfile.write(seq)
outfile.write("\n")
outfile.close()

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
Example output text file
xyz Coordinates
MODEL
ATOM   1n   0.0  1.0  2.0
new line
2.0

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: