- CodeCraft by Dr. Christine Lee
- Posts
- Jazz Up Your Olympics Board with PySimpleGUI! π
Jazz Up Your Olympics Board with PySimpleGUI! π
Customize Your Olympics Leaderboard: Reading and Writing to CSV Files with PySimpleGUI! π
Hey CodeCrafters! π¨
Are you ready to take your interactive leaderboard to the next level?
Today, we're going to learn how to read and write data to a CSV file.
This way, you can easily load your leaderboard from a file and save updates, making your app even more dynamic and practical.
Let's dive in!
What is a CSV File?
A CSV (Comma-Separated Values) file is a simple text file used to store tabular data. Each line in the file represents a row, and each value is separated by a comma. It's a common format for data exchange between applications. Think of it like a spreadsheet, but in plain text!
Step-by-Step Tutorial
1. Create Your CSV File
Create a CSV file using the sample data below:
Country | Gold | Silver | Bronze |
USA | 33 | 39 | 39 |
China | 33 | 27 | 23 |
Australia | 18 | 16 | 14 |
Japan | 16 | 8 | 13 |
UK | 14 | 20 | 23 |
France | 14 | 20 | 22 |
Korea | 13 | 8 | 7 |
Netherlands | 13 | 6 | 10 |
Germany | 12 | 9 | 8 |
Italy | 11 | 12 | 13 |
Canada | 7 | 6 | 11 |
New Zealand | 6 | 7 | 2 |
How to create the CSV file:
Creating a CSV file using Google Sheets is quick and easy!
Hereβs a step-by-step guide with sample data to get you started:
Step 1: Open Google Sheets
Go to Google Sheets and create a new blank spreadsheet.
Step 2: Enter Your Data
In the first row, enter your headers. For example:
A1:
Country
B1:
Gold
C1:
Silver
D1:
Bronze
Below the headers, enter your data. For example:
A2:
USA
B2:
33
C2:
39
D2:
39
A3:
China
B3:
33
C3:
27
D3:
23
A4:
Australia
B4:
18
C4:
16
D4:
14
Step 3: Download as CSV
Once your data is entered, go to the File menu.
Click on Download and then choose Comma-separated values (.csv, current sheet).
Your CSV file will be downloaded to your computer.
Step 4: Use Your CSV File
Now you can use this CSV file in your Python programs or any other application that supports CSV files!
Sample Data in CSV Format:
If you opened your CSV file in a text editor, it would look like this:
Country,Gold,Silver,Bronze
USA,33,39,39
China,33,27,23
Australia,18,16,14
Japan,16,8,13
UK,14,20,23
Thatβs it! Youβve created a CSV file using Google Sheets in just a few simple steps. π
2. Reading and Writing to the CSV File Using a Dictionary
Let's break down the code step by step:
Step 1: Reading the CSV File into a Dictionary
First, we'll create a function to read the CSV file and load the data into a dictionary. This makes it super easy to access and update our leaderboard.
import csv
def read_leaderboard(file_path):
leaderboard = {}
with open(file_path, mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
country = row['Country']
leaderboard[country] = {
'Gold': int(row['Gold']),
'Silver': int(row['Silver']),
'Bronze': int(row['Bronze'])
}
return leaderboard
This function opens the CSV file, reads each row, and stores the data in a dictionary. The DictReader
from the csv
module makes this easy by treating each row as a dictionary.
Step 2: Writing the Dictionary Back to the CSV File
Next, we'll create a function to save our dictionary back to the CSV file. This ensures any updates we make are stored.
def write_leaderboard(file_path, data):
with open(file_path, mode='w', newline='') as file:
fieldnames = ['Country', 'Gold', 'Silver', 'Bronze']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for country, medals in data.items():
row = {'Country': country, 'Gold': medals['Gold'], 'Silver': medals['Silver'], 'Bronze': medals['Bronze']}
writer.writerow(row)
This function opens the file in write mode and uses DictWriter
to write each dictionary entry as a row in the CSV file.
Step 3: Converting Dictionary to List for Display
We'll need a helper function to convert our dictionary to a list for displaying in the PySimpleGUI table.
def dict_to_list(leaderboard_dict):
leaderboard_list = []
for country, medals in leaderboard_dict.items():
leaderboard_list.append([country, medals['Gold'], medals['Silver'], medals['Bronze']])
return leaderboard_list
This function loops through the dictionary and creates a list of lists, each sublist representing a country and its medal counts.
Step 4: Building the GUI
Now let's set up our GUI layout and event loop using PySimpleGUI.
import PySimpleGUI as sg
# Read the initial leaderboard data
file_path = 'leaderboard.csv'
leaderboard = read_leaderboard(file_path)
# GUI Layout
layout = [
[sg.Text('Olympics Leaderboard')],
[sg.Table(values=dict_to_list(leaderboard), headings=['Country', 'Gold', 'Silver', 'Bronze'], key='-TABLE-')],
[sg.Text('Country'), sg.InputText(key='-COUNTRY-')],
[sg.Text('Gold'), sg.InputText(key='-GOLD-')],
[sg.Text('Silver'), sg.InputText(key='-SILVER-')],
[sg.Text('Bronze'), sg.InputText(key='-BRONZE-')],
[sg.Button('Update Leaderboard'), sg.Button('Save to File'), sg.Button('Exit')]
]
# Create the window
window = sg.Window('Olympics Leaderboard', layout)
# Event loop
while True:
event, values = window.read()
if event sg.WIN_CLOSED or event 'Exit':
write_leaderboard(file_path, leaderboard)
break
elif event == 'Update Leaderboard':
# Update the leaderboard dictionary with the new entry
country = values['-COUNTRY-']
gold = int(values['-GOLD-'])
silver = int(values['-SILVER-'])
bronze = int(values['-BRONZE-'])
leaderboard[country] = {'Gold': gold, 'Silver': silver, 'Bronze': bronze}
# Update the table with the new leaderboard
window['-TABLE-'].update(values=dict_to_list(leaderboard))
elif event == 'Save to File':
# Save the updated leaderboard to the CSV file
write_leaderboard(file_path, leaderboard)
window.close()
Letβs Sum it Up!
Reading the CSV File: The
read_leaderboard
function reads the data from the CSV file into a dictionary, with the country as the key and a dictionary of medal counts as the value.Writing to the CSV File: The
write_leaderboard
function writes the updated leaderboard data back to the CSV file from the dictionary.Converting Dictionary to List: The
dict_to_list
function converts the dictionary to a list format for displaying in the PySimpleGUI table.GUI Layout: The layout includes a table to display the leaderboard and input fields to add or update entries.
Event Loop: The event loop handles user interactions. When the 'Update Leaderboard' button is clicked, it updates the dictionary with the new entry. When the 'Save to File' button is clicked, it writes the updated leaderboard back to the CSV file. Before exiting, it ensures the dictionary data is saved to the CSV file.
Output
File loaded
Adding data
New data written to CSV
The completed code can be downloaded below:
|
Coding with a Smile π€£ π
Commentary King/Queen:
Becoming adept at writing comments in your code is like being a sports commentator. Youβre providing play-by-play action so that anyone (including future you) can understand whatβs happening without watching the entire game (reading the entire code).
Recommended Resources π
Big Desk Energy is by Tyler Denk who is currently the cofounder/ceo at beehiiv. Prior to that, he was the second employee at Morning Brew, where he spent his days up until the acquisition by Business Insider.
I gladly recommend his weekly newsletter where he shared his experiences, processes, and philosophies as a startup founder with a lot of strong opinions and absolutely no filter.
Letβs Inspire Future AI Coders Together! β
Iβm excited to continue sharing my passion for Python programming and AI with you all. If youβve enjoyed the content and found it helpful, do consider supporting my work with a small gift. Just click the link below to make a difference β itβs quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.
Thank you for being amazing!
Ready for More Python Fun? π¬
Subscribe to our newsletter now and get a free Python cheat sheet! π Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.
Keep learning, keep coding π©βπ»π¨βπ», and keep discovering new possibilities! π»β¨
Enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!
Stay tuned for our next exciting project in the following edition!
Happy coding!ππβ¨
π We want to hear from you! π How do you feel about our latest newsletter? Your feedback will help us make it even more awesome! |