File I/O (continued)
Winter 2025
1
Adrian Salguero
Announcements
2
Files and Filenames
3
Navigating File Directories
4
The path to a file you can use in your program
Navigating File Directories
5
Navigating File Directories
6
Opening/Reading a File
myfile = open(filepath)
for line in myfile:
# Read file contents
myfile.close()
myfile = open(filepath, “r”)
for line in myfile:
# Read file contents
myfile.close()
with open(filepath) as f:
# Read file contents
7
By default, file is opened for reading
Adding "r" makes read-only explicit.
Writing/Appending to a File
myfile = open(filepath, “w”)
# Write to your file
myfile.close()
myfile = open(filepath, “a”)
# Append (add) to your file
myfile.close()
8
Does the file exist?
Does the file not exist?
Adding "a" opens for appending.
Adding "w" opens for writing.
How does reading look like?
myfile = open(filename)
for line in myfile:
print(line)
myfile.close()
This is a line
More text
80, 50, 100
9
Line
“This is a line”
“More text”
“80, 50, 100”
Python reads these numbers as a string!
split() and strip() methods
10
Reading a file Example
# Count the number of words in a text file
in_file = "song.txt"
myfile = open(in_file)
num_words = 0
for line_of_text in myfile:
word_list = line_of_text.split()
num_words += len(word_list)
myfile.close()
print("Total words in file: ", num_words)
11
Writing to a file Example
# Replaces any existing file of this name
myfile = open("output.dat", "w")
# Similar to printing output
myfile.write("a bunch of data")
# but you must add newline if desired, unlike print
myfile.write("a line of text\n")
# and the argument must be a string
myfile.write(4)
myfile.write(str(4))
myfile.close()
12
open for Writing�(give no argument, or
"r", for Reading)
“\n” means end of line (Newline)
Incorrect; results in:
TypeError: expected a character buffer object
Similar to if you tried to do print(4)
Correct. Argument must be a string
close when done with all writing
Next thing written will be on this same line.
Generate 100 rows of random “data”
import random
myfile = open("sample_data.dat", "w")
for i in range(100):
for j in range(9):
myfile.write(str(random.randint(0, 100)))
myfile.write(",")
myfile.write(str(random.randint(0, 100)))
myfile.write('\n')
myfile.close()
13
Practice Problem
Suppose we have many, many rows of data separated by commas (csv files!). Write a Python program that reads the data line by line, calculates the average value of each row, and prints out a list of all the average values.
Bonus: instead of printing out the list, write the averages, line by line, to a new file
14
Solution: Practice Problem
Will be posted after class
15