TEC102 Week 10 Workshop
TEC102 Week 10 Workshop
Fundamentals of
Programming
Lesson 10
Files
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
The material in this communication may be subject to copyright under the Act. Any
further reproduction or communication of this material by you may be the subject of
copyright protection under the Act.
print(data)
# Load this file into your Python program
Source: https://www.geeksforgeeks.org/with-statement-in-python/
Iterating Through Lines
(Activity)
• Similarly to the previous slides:
1. Open the file “students.txt” (on the LMS)
2. Use .readlines() method to read line by
line (as opposed to .read() method)
with open('students.txt') as file:
for line in file.readlines():
print(line)
"""
Jing
Jim
Kerrie
Rakesh
"""
Activity
Notice in the previous slide, the code output
generated a new line for each student output
1. Why’s this the case?
2. How can we ensure that there are no new lines
for each student output?
Answer:
1. Because readlines() adds a new line escape
character \n for each student output
2. Use print(line.strip()) to remove new line
escape character \n
Writing a File (Activity)
• Instead of reading a file, we will attempt to write a file
– Note: There is no file on the LMS. You may call the file
whatever you like, e.g. file.txt
with open('file.txt', 'w') as file:
file.write('Testing if data added to file')
• Notice in this case, we passed an argument ‘w’ to the
open() function, which indicates open the file in write
mode
– The default argument is ‘r’ (or read mode)
– By not changing the argument to write mode, you will NOT
be able to write to the file
• When file.txt is manually opened, it should look like
this:
Append to a File (Activity)
• We can append to an existing file without
completely overwriting existing files
– Make sure to apply the ‘a’ argument for
append mode
with open('file.txt', 'a') as file:
file.write('Append mode\n')
# \n used to add new line
Comma Separated Value (CSV)
File
• CSV files are an example of a text file that
impose a specific structure to the data
– Data is separated by a comma ,
• You may be familiar if you used Microsoft
Excel or Google Sheets, the file extension is
*.csv
• CSV files are simply just text – even if the
*.csv file extension wasn’t present, as long as
the data had a proper structure, we can read
the CSV file and manipulate it in our Python
program
Reading a CSV File (Activity)
• Open the file “gradebook.csv” (on the LMS)
import csv
gradebook = {}
with open('gradebook.csv', newline='') as file:
data = csv.DictReader(file)
for row in data:
gradebook[row['student']] = row['grade']
Note the following:
• Using a csv library
• Using the csv library’s DictReader object – which converts data into
a dictionary
• The data variable (DictReader object) is looped
• The gradebook dictionary is populated by applying each student’s
name as the key and each student’s grade as the value to that key
Reading a CSV File (2)
(Activity)
• In the previous example, gradebook.csv contained a
header ‘student,grade’
• Assuming the CSV file does not contain this header,
and just CSV data
– Open the file “gradebook_headers_removed.csv” (on
the LMS)
import csv
• An elegant solution!
Writing a CSV File (Activity)
• Instead of reading a CSV file, we will attempt to
write to a CSV file
– Note: There is no file on the LMS. You may call the
file whatever you like, e.g. output.csv
• Using the original gradebook dictionary to
output to a CSV file:
import csv
print(data)
# {'user': 'James', 'action': 'Buy', 'item_id': 78192, 'price': 39.99}
convert_to_JSON = {
'number': 123,
'float': 1.32,
'bool': True,
'NoneType': None,
'String': 'String',
'datetime': '2022-12-27 08:26:49.219717'
}
Answer: