1 of 11

CS 149

Professor: Alvin Chao

File I/O

  • Reading Chp 9 Tonight 11pm
  • **Wed 11pm PA1B scoring_dice and tests
  • Thu 11pm Lab Coverage
  • Thu Actual Quiz 4 in class

2 of 11

Importing a Module

  • The following code creates a new file (in the current/default folder) named out.txt and writes several lines of output. Run the code.

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()

out.txt��Example output text file

xyz Coordinates

MODEL

ATOM 1n 0.0 1.0 2.0

3 of 11

Questions

a) How many arguments are passed to open? What are their types?

b) What variable stores the file object returned by the open function?

c) Identify the names of all methods used on this file object in the code.

d) What type of data does the write method require for its argument?

4 of 11

out.txt

Based on the out.txt file:�a) How many times was the write method called to create the first line of text?

b) How many times was the write method called to create the second line of text?

c) What does the "\n" character do when writing to the file?

d) How is the write method different from the print function?

5 of 11

What does this code do?

outfile = open("lines.txt", "w")

for i in range(1, 101):

outfile.write(f"Line #{i}\n")

outfile.close()

6 of 11

Append to a file

Python Code

Shell Ouput

afile.write("new line\n")

NameError: name ’afile’ is not defined

afile = open("out.txt", "a")

afile.write("new line\n")

9

afile.write(2.0)

TypeError: write() argument must be str, not float

afile.write("2.0")

3

afile.close()

afile.write("new line\n")

ValueError: I/O operation on closed file.

7 of 11

Read from a file

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]

8 of 11

Observations

What type does readline return? Readlines?

What is returned if you try to read past the end of the file?

What is the difference in the for loops?

9 of 11

File read

Write a program to read from a file called names.txt that has the first and last names of 5 presidents, one name per line (i.e. Abraham Lincoln) Write a program to list all the last names (second word of each line).

George Washington�Abraham Lincoln�Thomas Jefferson�James Madison�John Adams

10 of 11

PI Question

11 of 11

  • Acknowledgements

Copyright © 2023 C. Mayfield, T. Shepherd, and H. Hu. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

</end>