CSE 160 Section 6
File I/O
CSE 160: Section 6
Logistics
CSE 160: Section 6
Lecture Review: File I/O
CSE 160: Section 6
File I/O
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
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
Section Handout Problems
CSE 160: Section 6
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
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
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
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
Problem 3
For example, write_list(["Reign", "Kraken", "Storm", "Mariners"], "sports.txt") would make sports.txt contain:
Reign
Kraken
Storm
Mariners
CSE 160: Section 6
Problem 3
def write_list(lst, filename):
f = open(filename, "w")
for item in lst:
f.write(item + "\n")
f.close()
CSE 160: Section 6
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
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
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
Problem 4:
rocks.txt contains the following:
Sedimentary
Metamorphic
Igneous
f = open("rocks.txt")
contents = f.read()
print(len(contents))
for rock in f:
print(rock)
f.close()
CSE 160: Section 6
Problem 4a:
rocks.txt contains the following:
Sedimentary
Metamorphic
Igneous
31
Counts the number of characters in rocks.txt
CSE 160: Section 6
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
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
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
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
Thanks for Coming!
CSE 160: Section 6