“Auto-save” can be done by adding an open, .write, and .close function at the end of the inside of a loop, e.g.
f = open("calendar.txt", "w") # Permissions set to 'w' because we are deleting the file and replacing it with the whole 2D list every time.
f.write(str(myEvents)) # Need to cast the list to a single string
f.close()
👉 eval()
takes the text from the file, converts it into running code, and assigns it to myEvents[]
as a 2D list. Good, eh?
The new construct to get around errors is called try.... except
myStuff = []
try:
f.open("Stuff.mine","r")
myStuff = eval(f.read())
f.close()
# Try to find a file called 'Stuff.mine' and open it
except:
print("ERROR: Unable to load")
# If the file can't be found, show the error instead of crashing the whole program
for row in myStuff:
print(row)
there are problems with just putting the whole code in a 'try except'.
to know what sort of error has occurred, you can tell except
what type of erros to look for
Exception
(capital 'E') means 'every type'. I've captured the error type in the 'err' variable and printed it out to tell me what the error is.
Here's a list
of some built in except
error codes.
except Exception as err:
print("ERROR: Unable to load")
print(err)
We could even get rid of the 'err' variable entirely and print a traceback, which will show you the red error tracing you see when python crashes.
debugMode = True
myStuff = []
try:
f.open("Stuff.mine","r")
myStuff = eval(f.read())
f.close()
# Try to find a file called 'Stuff.mine' and open it
except Exception:
print("ERROR: Unable to load")
if debugMode:
print(traceback)
for row in myStuff:
print(row)
try
is not finished without an except.
Replit code for pizza program (the solution walkthrough was really helpful too)
new function learned:
also: except, pass (”silences any and all exceptional conditions that come up while the code covered in the try: block is being run”) - apparently it’s bad coding practice though, but essentially just means skip past doing anything with the error that is found
Python has built-in libraries for csvs
👉 join
allows us combine lists in a more interesting way
import csv
with open("January.csv") as file:
reader = csv.reader(file)
line = 0
for row in reader:
print (", ".join(row)) # adds a comma and space and then joins data, you could try joining with tabs too with `\\t`
👉 The trick is to treat the CSV like a dictionary, using the csv.DictReader()
function. In the code below, I've filtered it so that it only shows the net total from each day
import csv # Imports the csv library
with open("January.csv") as file:
reader = csv.DictReader(file) # Treats the file as a dictionary
line = 0
for row in reader:
print (row["Net Total"])
adding net totals from each day to create a total - notice the casting data as a float because library treats it as text