CSE 160
File IO
Hannah Cheung
Announcements
2
Files
3
File objects and filenames
4
Types of filenames
5
Filename Examples
6
Current Working Directory
import os
print(“Current working directory is”, os.getcwd())
7
Opening Files
# Takes a filename and returns a file object.
# Fails if file cannot be found and opened.
# By default, file is opened for reading.
my_file = open(“datafile.dat”)
my_file = open(“data.file.dat”, “r”)
# Opens file for writing.
# Creates given file if it does not exist. If file
# already exists, then it will be overwritten.
my_file = open(“datafile.dat”, “w”)
# Writing/appending to already-existing file.
my_file = open(“datafile.dat”, “a”)
8
Reading Files
# Takes a filename and returns a file object.
# Fails if file cannot be found and opened.
# By default, file is opened for reading.
my_file = open(“datafile.dat”)
# Approach: Process one line at a time
for line_of_text in my_file:
…process line_of_text
# Approach 2: Process entire file at once
all_data_as_big_string = my_file.read()
# close the file when done reading
my_file.close()
9
Reading File Example
# Reads in file one line at a time and
# prints contents of the file.
in_file = “student_info.txt”
my_file = open(in_file)
for line_of_text in my_file:
print(line_of_text)
my_file.close()
10
Reading File Example
# Count number of words in text file.
in_file = “student_info.txt”
my_file = open(in_file)
num_words = 0
for line_of_text in my_file:
word_list = line_of_text.split()
num_words += len(word_list)
my_file.close()
print(“Total words in file:”, num_words)
11
Reading a file multiple times
12
my_file = open(“datafile.dat”)
for line_of_text in my_file:
…process line_of_text
# loop will not be executed
for line_of_text in my_file:
…process line_of_text
Reading a file multiple times
13
my_file = open(“datafile.dat”)
lines = []
for line_of_text in my_file:
lines.append(line_of_text)
for line_of_text in lines:
…process line_of_text
for line_of_text in lines:
…process line_of_text
Reading a file multiple times
14
my_file = open(“datafile.dat”)
for line_of_text in my_file
…process line_of_text
my_file = open(“datafile.dat”)
for line_of_text in my_file:
…process line_of_text
Writing to Files
15
# Replaces any existing file of this name
my_file = open(“datafile.dat”, “w”)
# Similar to printing output, except must
# explicitly specify new lines using \n
my_file.write(“a bunch of data”)
my_file.write(“a line of text\n”)
# Argument provided must be a string
my_file.write(4) # Error!
my_file.write(str(4))
# close the file when done writing
my_file.close()