11 – File I/O
COMP 125 – Programming with Python
Recording Disclaimer
The synchronous sessions are recorded (audiovisual recordings). The students are not required to keep their
cameras on during class.
The audiovisual recordings, presentations, readings and any other works offered as the course materials aim
to support remote and online learning. They are only for the personal use of the students. Further use of
course materials other than the personal and educational purposes as defined in this disclaimer, such as
making copies, reproductions, replications, submission and sharing on different platforms including the digital
ones or commercial usages are strictly prohibited and illegal.
The persons violating the above-mentioned prohibitions can be subject to the administrative, civil, and
criminal sanctions under the Law on Higher Education Nr. 2547, the By-Law on Disciplinary Matters of Higher
Education Students, the Law on Intellectual Property Nr. 5846, the Criminal Law Nr. 5237, the Law on
Obligations Nr. 6098, and any other relevant legislation.
The academic expressions, views, and discussions in the course materials including the audio-visual
recordings fall within the scope of the freedom of science and art.
COMP 125 Programming with Python 2
File I/O Basics
How can we save data for later use?
▪ Word processors: write letters, reports, etc.
▪ Image editors: draw graphics and edit images
▪ Spreadsheets: insert numbers and mathematical formulas
▪ Games: list of player names, scores, current game status
▪ Web browsers: contents of shopping carts, etc.
You will learn:
▪ How to open a file
▪ How to read from a file
▪ How to write into a file
▪ How to close a file
COMP 125 Programming with Python 4
Filenames and file objects
▪ Files are identified by a filename
▪ Examples: [Link] , [Link] ,
[Link]
▪ Filename extensions represent the
type of data stored
▪ Examples: .jpg, .txt , .docx, .py
▪ The program must create a file
object in memory to work with a file
on the computer’s disk
COMP 125 Programming with Python 5
Opening a file
name of the variable
referencing the file object
string specifying the
name of the file
Mode in which the file will
be opened (reading, writing, etc.)
Some of the file open modes:
Method Description
‘r' Open a file for reading only. The file cannot be changed or written to.
‘w’ Open a file for writing. If the file already exists, erase its contents. If it doesn ot exist, create it.
‘a’ Open a file to be written to. All data written to the file will be appended to its end. If the file does not exist, create it.
COMP 125 Programming with Python 6
Closing a file
▪ Do not forget to close the file once you are done
▪ close() disconnects the program from the file to prevent data loss
COMP 125 Programming with Python 7
File locations - paths
▪ Files are kept on the secondary storage using file systems
▪ Almost all common file systems organize files into hierarchies (which form a
tree) using drives and folders
COMP 125 Programming with Python 8
File locations - paths
▪ When opening files, you can specify an absolute path or a relative path
▪ Relative path is relative to the “current working directory (cwd)”
▪ To learn the current working directory:
COMP 125 Programming with Python 9
File locations - paths
▪ When file is in the same folder as the Python program (or nearby), using
relative paths makes things easy:
▪ Examples with absolute paths:
▪ Mac:
▪ Windows:
Specifies that the string is a raw string
(backlash characters are read as literal backslashes)
▪ If you need to, you should use relative paths in the homework (why?)
COMP 125 Programming with Python 10
Writing data into a file
It accepts a single string
as an argument
Don’t forget to close the file
once you are done!
COMP 125 Programming with Python 11
Example
▪ Grocery list: write each item and it’s quantity on a separate line in a file.
items = ["bread", "butter", "eggs", "milk", "pasta"]
quantity = [2, 1, 12, 3, 2]
fvar = open("grocery_list.txt", "w")
for i in range(len(items)):
[Link](items[i]+"\t"+str(quantity[i])+"\n")
[Link]()
COMP 125 Programming with Python 12
Example
▪ Add 5 bananas at the end of the file that you created in the previous
example.
fvar = open("grocery_list.txt", "a")
[Link]("banana"+"\t"+str(5)+"\n")
[Link]()
COMP 125 Programming with Python 13
Reading data from a file
▪ Open your file for reading (with ‘r’ method)
▪ Use the readline method to read one line at a time
▪ readline: File object function that reads a line from the file
▪ Line returned as a string, including ‘\n’
Alternatives
▪ read: File object function that reads entire file contents into memory
▪ Contents returned as a string
▪ readlines: File object function that reads entire file contents
▪ Contents returned as a list of lines where each line is a string including ‘\n’
COMP 125 Programming with Python 14
Using readline
▪ Reads the file contents, one line at a time
COMP 125 Programming with Python 15
Example
▪ Suppose that you have the following file that
contains the department abbreviations and the
course codes separated with white space.
readline returns empty string
when End of File is reached
▪ Write a function that takes the name of this file
as its input, reads its contents, and returns a list
of course tuples. You may assume that the file
content is always valid.
COMP 125 Programming with Python 16
Using a for loop
▪ for loop automatically reads the lines in a file
▪ without requiring a priming read operation
▪ without testing a special condition that signals the end of the file
COMP 125 Programming with Python 17
Example (using for)
COMP 125 Programming with Python 18
Alternative way to open a file: ’with’ statement
[Link]() is not required
COMP 125 Programming with Python 19
Common errors
▪ What happens if your input file does not exist?
COMP 125 Programming with Python 20
Common errors
▪ What happens if the path of your output file does not exist?
COMP 125 Programming with Python 21
How to handle exceptions
▪ Try/Except body captures the error and lets you decide how to handle it.
COMP 125 Programming with Python 22
File I/O with String Formatting
Some useful functions to process strings
rstrip(): returns a copy of the string with all
trailing whitespace characters are removed (at
the end, i.e., Right side)
▪ Useful to get rid of the newline character
lstrip(): returns a copy of the string with all
leading whitespace characters are removed
(at the beginning, i.e., Left side)
strip(): returns a copy of the string with all
leading and trailing whitespace characters are
removed
COMP 125 Programming with Python 24
Reading and writing numeric data
Now you can perform
math operations
25
COMP 125 Programming with Python
Example
▪ Write a function that creates an output
file with name number_list.txt and writes
the numbers 1 through 100 to that file.
▪ Write a function that opens the
number_list.txt file you created, reads
the numbers from the file, and displays
them.
▪ Write a function that adds all numbers it
read from the number_list.txt file and
displays their total.
COMP 125 Programming with Python 26
Example
▪ Suppose that you have the following file that contains the exam grades of students
▪ Write two functions:
▪ The first function takes the name of this file as its input, reads its contents, and returns a list of student tuples. The fi rst
item in each tuple is the student id as a string and the second item is a list of three integer grades. You may assume
that the file always contains valid content.
▪ The second function takes the list of student tuples together with an output file name as its inputs. For each student, it
calculates the average of the grades and saves these averages in the output file together with the students’ IDs.
COMP 125 Programming with Python 27
Solution
COMP 125 Programming with Python 28
CSV Files
Working with CSV files
▪ CSV file = “comma separated values” file
▪ Each line of the file is a data record
▪ Each record consists of one or more fields, separated by commas
▪ How to edit CSV files?
▪ Spreadsheet Apps
▪ MS Excel, Apple Numbers,
Google Sheets, OpenOffice or
LibreOffice
▪ Text Editing Apps
▪ WordPad, TextEdit, Vim, Emacs,
etc.
▪ Programming Editor Apps
▪ Spyder, PyCharm, VS Code, etc.
CSV = comma-separated values
COMP 125 Programming with Python 30
CSV files
Spreadsheet view: Text editor view:
31
Writing data into a .csv file
▪ Writing into the same column
If not string, use
str to convert to a
string
▪ Writing into the same row
COMP 125 Programming with Python 32
Reading data from a .csv file
▪ Reading the items from a column
▪ Reading the items from a row
COMP 125 Programming with Python 33
Example
▪ Proteins are composed of 20 different types
of amino acids.
▪ The sequence of a protein can be shown by
using the single letter representation for each
amino acid. (e.g. Glycine: G)
▪ Ubiquitin amino acid sequence:
“MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDK
EGIPPDQQRLIFAGKQLEDGRTLSDYNIQKES
TLHLVLRLRGG”
COMP 125 Programming with Python 34
Example atomid atom name
x, y, z coordinates
▪ The file [Link]
contains atom information
for the protein 1ubq
▪ From the lines starting
with ATOM keyword, copy
the following to a new csv
file:
▪ atomid
▪ atom name
▪ x, y, z coordinates
COMP 125 Programming with Python 35
Solution
COMP 125 Programming with Python 36