1 of 15

File I/O (continued)

Winter 2025

1

Adrian Salguero

2 of 15

Announcements

  • Midterm information now available on the website
  • Midterm practice problems also available on the website
  • Homework 3 due tonight at 11:59pm
  • Homework 4, Part 1 will be released on Monday
  • Coding Practice 4 now available, due Wednesday February 5th at 11:59pm

2

3 of 15

Files and Filenames

  • A filename states where your program should look for the given file
    • Paths are how we specify where to search for these files
    • Without the correct path, our program does not know how to search for a file
    • Step by step instructions on how to reach a file
  • Relative/Absolute directories
    • Relative: give instructions starting from where you are currently at
    • Absolute: give instructions starting from the first drive

3

4 of 15

Navigating File Directories

  • Which directory am I in? Where am I in my computer?
    • Can also use pwd to print the current working directory or current folder or current location in your computer you are in

4

The path to a file you can use in your program

5 of 15

Navigating File Directories

  • How can I tell which folders exist in my current directory/location?
    • Type ls into your terminal → this will list all the folders and files held in your current directory

5

6 of 15

Navigating File Directories

  • How do I change directories? How do I move into a folder? Or out of a folder?
    • cd <folder_name/directory_name> to enter the folder
    • cd .. to go “up” on folder or one directory

6

7 of 15

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.

8 of 15

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?

  • “w” will overwrite it
  • “a” will add to it

Does the file not exist?

  • Both “w” and “a” will create it

Adding "a" opens for appending.

Adding "w" opens for writing.

9 of 15

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!

10 of 15

split() and strip() methods

  • split([delimiter]) - returns a list of strings that are separated by a given delimiter. If no delimiter is specified, defaults to blank space

  • strip([character]) - removes any leading or trailing characters. If no characters are specified, defaults to white space

10

11 of 15

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

12 of 15

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.

13 of 15

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

14 of 15

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

15 of 15

Solution: Practice Problem

Will be posted after class

15