0% found this document useful (0 votes)
56 views18 pages

TEC102 Week 10 Workshop

The convert_to_JSON dictionary contains Python data types like int, float, bool etc. When dumped to a JSON file using json.dump(), the data types are converted to JSON-compatible types like number, strings etc. so the output.json file will contain JSON format rather than a Python dictionary.

Uploaded by

aiexplorer009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views18 pages

TEC102 Week 10 Workshop

The convert_to_JSON dictionary contains Python data types like int, float, bool etc. When dumped to a JSON file using json.dump(), the data types are converted to JSON-compatible types like number, strings etc. so the output.json file will contain JSON format rather than a Python dictionary.

Uploaded by

aiexplorer009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

TEC102

Fundamentals of
Programming
Lesson 10
Files
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or on behalf of


Kaplan Business School pursuant to Part VB of the Copyright Act 1968 (the Act).

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.

Do not remove this notice.


Subject Learning Outcomes
1 Interpret simple program
specifications.
2 Conceptualise a high-level model via the
use of pseudocode and flow charts.
3 Describe how to transfer a high-level
model into a software application via the
use of a programming language.
4 Use an integrated development
environment to develop, debug and
test a solution written in a
programming language.
5 Use a programming language to read
and write data to a persistent storage.
Files
• Computers utilise file systems to retrieve and
store data
• Each file has data, even the programs you’ve
created, such as main.py is a file
• In the next slide, we will attempt to load a file
called “file_to_test.txt” (which you should
download from the LMS, to your local working
directory – ensure it’s in the same location as
your existing Python file, i.e. main.py)
Reading a File (Activity)
• Let’s all attempt to open the file “file_to_text.txt”
into your Python program, as shown below:
with open('file_to_test.txt') as file:
data = file.read()

print(data)
# Load this file into your Python program

• The expected output is shown above, if you didn’t


get this or there were issues, please let your
workshop facilitator know
– We will attempt many read/write to a file activities, if
there are any issues, again, please let your workshop
facilitator know
Notes on with keyword
• The with keyword is used in exception
handling for file streams
Without with With with

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

with open('gradebook_headers_removed.csv') as file:


reader = csv.reader(file)
gradebook = dict(reader)

• 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

gradebook = {'Jing': '35', 'Jim': '50', 'Kerrie': '65', 'Rakesh': '85'}


with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
for key, value in gradebook.items():
writer.writerow([key, value])
JavaScript Object Notation (JSON)
File
• Similarly to CSV file, JSON file is another
common text file that imposes a specific
structure to the data
– Data structure defines objects and arrays
– Worth noting that just because a file extension
has *.json in the name doesn’t ensure the
data structure conforms to a valid JSON
format
Reading a JSON File (Activity)
• Open the file “purchase.json” (on the LMS)
import json

with open('purchase.json') as file:


data = json.load(file)

print(data)
# {'user': 'James', 'action': 'Buy', 'item_id': 78192, 'price': 39.99}

Note the following:


• Using a json library
• Using the json library’s load method – which
reads file data into the variable data
Writing a JSON File (Activity)
• Instead of reading a JSON file, we will attempt to
write to a JSON file
– Note: There is no file on the LMS. You may call the
file whatever you like, e.g. output.json
import json

convert_to_JSON = {
'number': 123,
'float': 1.32,
'bool': True,
'NoneType': None,
'String': 'String',
'datetime': '2022-12-27 08:26:49.219717'
}

with open('output.json', 'w') as file:


json.dump(convert_to_JSON, file)
Activity
In the previous slide,
what are some
differences between the
convert_to_JSON
dictionary and JSON
format in the
output.json file?

Answer:

You might also like