1 of 22

CSE 160 Section 6

File I/O

CSE 160: Section 6

​

2 of 22

Logistics

  • Practice 4 (Lists) due tomorrow, Fri Nov 6 at 11:59pm
    • Submit on Gradescope, no late submissions!
    • 2+ correct solutions = 1 practice point
  • HW3: Image Processing is out!
    • Due Tue Nov 17 at 11:59pm
    • Two weeks, but start early!
  • Quest 2 next Monday, Nov 9 in class

CSE 160: Section 6

​

3 of 22

Lecture Review: File I/O

CSE 160: Section 6

​

4 of 22

File I/O

​

  • A file stores data on your computer. Use open() to read or write it
  • "r" reads, "w" overwrites, "a" adds to the end
  • Each line you read is a string that ends with "\n"
  • Close it when you’re done (or use with)

f = open("data.csv") # mode "r" (read) by default

for line in f: # line = "1, 2, 5, 0\n"

line.strip() # "1, 2, 5, 0"

line.strip().split(",") # ["1", " 2", " 5", " 0"]

f.close() # close when you're done

​

CSE 160: Section 6

​

5 of 22

File I/O

# Opening a file

f = open(path, mode)

f.close()

with open(path, mode) as f:

​

# Reading and writing

f.read()

for line in f:

f.write(s)

​

# Cleaning a line

line.strip()

line.split(",")

# Cleaning a line

line.strip()

line.strip(",")

​

​

Syntax

Description

open(path, mode)

Open a file. Mode: "r" read (default), "w" overwrite, "a" append

f.read()

Return the entire file as one string

for line in f:

Loop through the file one line at a time

f.write(s)

Write string s to the file (strings only; add "\n" yourself)

f.close()

Close the file when you're done

with open(path, mode) as f:

Open a file; closes it automatically

s.strip() / s.strip(",")

Remove whitespace (like “\n”), or the given character, from both ends only

s.split(",") / s.split()

Split s into a list of strings at each “,”; with no argument, split on whitespace

CSE 160: Section 6

​

6 of 22

Section Handout Problems

CSE 160: Section 6

​

7 of 22

Warm-Up Problem

What are the contents of secret.txt after this code runs?

​

f = open("secret.txt", "w")

f.write("Thanksgiving ")

f.write("is in\n")

f.write("November")

f.close()

f.write("26th")

f.open("secret.txt", "a")

f.write("next next week\n")

f.close()

​

​

CSE 160: Section 6

​

8 of 22

Warm-Up Problem (Solutions)

What are the contents of secret.txt after this code runs?

​

f = open("secret.txt", "w")

f.write("Thanksgiving ")

f.write("is in\n")

f.write("November")

f.close()

f.write("26th")

f.open("secret.txt", "a")

f.write("next next week\n")

f.close()

​

Thanksgiving is in

November

CSE 160: Section 6

​

9 of 22

Problem 1

Write a function called count_lines(filename) that reads the file and returns the total number of lines in the file.

For example, if you had a file birds.txt that contains:

​

Raven

Crow

Penguin

Flamingo

​

The returned value of count_lines("birds.txt") would be 4

CSE 160: Section 6

​

10 of 22

Problem 1 (Solutions)

Write a function called count_lines(filename) that reads the file and returns the total number of lines in the file.

​

def count_lines(filename):

f = open(filename)

count = 0

​

for line in f:

count = count + 1

​

f.close()

return count

​

​

​

CSE 160: Section 6

​

11 of 22

Problem 3

  1. Write a function called write_list(lst, filename) that writes each string in lst to the file on its own line. You can replace the existing contents of the file (if applicable).

​

For example, write_list(["Reign", "Kraken", "Storm", "Mariners"], "sports.txt") would make sports.txt contain:

Reign

Kraken

Storm

Mariners

CSE 160: Section 6

​

12 of 22

Problem 3

  • Write a function called write_list(lst, filename) that writes each string in lst to the file on its own line. You can replace the existing contents of the file (if applicable).

​

def write_list(lst, filename):

f = open(filename, "w")

​

for item in lst:

f.write(item + "\n")

​

f.close()

​

​

CSE 160: Section 6

​

13 of 22

Problem 3

b. What would you change to your answer in part A if you did NOT want to erase the contents that were previously in the file?

​

​

We would change the "w" to an "a" while opening the file.

​

def write_list(lst, filename):

f = open(filename, "a")

​

for item in lst:

f.write(item + "\n")

​

f.close()

​

CSE 160: Section 6

​

14 of 22

Exit Ticket

Samaira opens her lab_report, but she doesn’t see her data. What could be wrong, and how could she fix it?

​

def lab_report(filename, data):

f = open(filename)

for number in data:

f.write(str(number) + "\n")

CSE 160: Section 6

​

15 of 22

Exit Ticket

​

By default, open(filename) opens the file in read mode ("r") so trying to write to it using f.write() will cause an error. We need to use "w" to open the file in write mode and add f.close() at the end to make sure our changes are saved and the file is properly closed.

​

def lab_report(filename, data):

f = open(filename, "w")

for number in data:

f.write(str(number) + "\n")

f.close()

​

​

​

CSE 160: Section 6

​

16 of 22

Problem 4:

rocks.txt contains the following:

​

Sedimentary

Metamorphic

Igneous

​

  1. What does the code below print?

​

f = open("rocks.txt")

contents = f.read()

print(len(contents))

for rock in f:

print(rock)

f.close()

CSE 160: Section 6

​

17 of 22

Problem 4a:

rocks.txt contains the following:

Sedimentary

Metamorphic

Igneous

  • What does the code below print?

​

​

31

Counts the number of characters in rocks.txt

CSE 160: Section 6

​

18 of 22

Problem 4b:

B. What does the code below print?

​

f = open("rocks.txt")

for rock in f:

print(rock)

f.close()

​

​

CSE 160: Section 6

​

19 of 22

Problem 4b:

B. What does the code below print?

​

f = open("rocks.txt")

for rock in f:

print(rock)

f.close()

​

Sedimentary

​

Metamorphic

​

Igneous

​

Each line keeps its "\n", and print() adds another one, so blank lines appear between lines.

​

CSE 160: Section 6

​

20 of 22

Problem 2

Line Number

Contents

1

Hydrogen

2

Helium

3

​

4

Lithium

5

​

6

Beryllium

7

​

8

​

9

Boron

Write a function called blank_lines(filename) that returns the number of empty lines in the file.

​

For example, if you had a file periodic_table.txt that contains the content shown on the right-hand side,

​

The returned value of blank_lines("periodic_table.txt") should return 4

CSE 160: Section 6

​

21 of 22

Problem 2 (Solutions)

def blank_lines(filename):

count = 0

​

with open(filename, "r") as f:

for line in f:

if line.strip() == "":

count = count + 1

​

return count

​

Line Number

Contents

1

Hydrogen

2

Helium

3

​

4

Lithium

5

​

6

Beryllium

7

​

8

​

9

Boron

CSE 160: Section 6

​

22 of 22

Thanks for Coming!

CSE 160: Section 6

​