Hi there!
This is a good introduction into file parsing for any programmer. All code below assumes Python 3 is being used. So lets start by thinking through what all we need:
- A way to read the file
- A way to keep track of all of our accounts (the single letters)
- A way to track their running totals (the number values)
- A way to parse out whether we are depositing into the account (<) or withdrawing from the account (>)
Lets tackle that first bullet point first. Reading the file. Luckily we are in Python so its super simple:
myfilevariable = open('accounts.txt', 'r')
Lets take this piece of code for just a second to go over it. Its broken into a few parts so let me break each part down in case you need it later.
- accounts.txt -> Path to the file you wish to open. (Don't forget to put the whole path to where it is saved!)
- r -> How you want to open the file. In this case it means read only mode.
Ok back to the main point. Weve opened the file. So now what do we do. Well we need the data out of it of course. There are a few ways to do this. But im going to go with the most straight forward in my head. We read all the lines into one big list and then parse them one by one.
LinesoftheFileIJustRead = myfilevariable.readlines()
Next up we need a structure to hold our list of accounts and their balances! Easy peasy. Python has a structure perfect for this called a Dictionary. A dictionary works by pairing two items together. In this case it would be our account name and our account balance. When you ask a Dictionary for its "Key" (Account name) it will return its current value (Balance).
DictionaryofAccountsandBalances = dict()
The "= dict()" tells Python that we want this to be a dictionary. Next up is just to loop over the lines and parse out what we need. Time for the meat!
for line in LinesoftheFileIJustRead:
splitline = line.split()
account = splitline[0]
addorsubtract = splitline[1]
amount = splitline[2]
This is alot more code in one spot then I wrote before so lets break it all down to figure out what im doing. the first line is telling python that for each line of text in our big list we are going to do the subsequent actions. Which means we are going to loop over all the lines. Then we are going to split that line open by the white spaces. That means that the "splitline" object is a list of strings that were separated by spaces (.split uses whitespace by default) so it would have a list of items from the line. And our prompt gives us the order. The first part of the split is the account name, the second is the operator < or > and the last is the amount of money! Python starts counting at 0 so we can split those values into individual variables to help!
Alrighty! We are almost done dont worry! Now that we have all the info we can now actually work! We now have to figure out are we adding or subtracting.
if addorsubtract == '<':
DictionaryofAccountsandBalances[account] = DictionaryofAccountsandBalances.get(account, 500) + int(amount)
elif addorsubtract == '>':
DictionaryofAccountsandBalances[account] =
DictionaryofAccountsandBalances.get(account, 500) - int(amount)
The if statements are pretty self explanatory from the prompt if its a '<' we add and if its a '>' we subtract. The rest might be a bit confusing so lets go over it. Before the equal we are looking into the dictionary for a key and setting it equal to the confusing part! After the equal might be a bit confusing but the .get function will look into the dictionary for that specific key and if it doesnt find it it will add it to the dictionary and set the inital value to 500 (from the prompt) then it will add the value from the text file to it and set it back equal. Which is all a confusing jumble of words right? Lets break it down one line at a time. Lets imagine we have these 3 lines starting fresh pretending there is no other data.
a > 280
a < 400
b < 900
What the above code will do is it will look into the dictionary for 'a' and see we dont have an account named 'a'. So it will set it up and make it have 500 dollars inside. Then it will withdraw the 280 and set the new balance to the account to be 220.
Next it will look in the dictionary for 'a' again. It will see it does exist and grab the value of 220 and add 400 to it and set the new value to be 620.
Next it will look in the dictionary for 'b' when it doesnt find it it will set it up with a balance of 500 and then add 900 to it and then set it equal to 1400.
It will keep doing that for every line in the text file. Finally, its time to print our running totals!
for key, value in DictionaryofAccountsandBalances.items():
print(key,value)
Alrighty! We are back to our favorite thing, the for loop! Here we are saying print every key and value pair (Account and Balance). Nice and easy nothing to it no tricks just an easy print! That will give you your final values!
All code with comments to help!
# Open the file into a file variable.
myfilevariable = open(accounts.txt, 'r')
# Read the file into a list
LinesoftheFileIJustRead = myfilevariable.readlines()
# Declare a dictionary.
DictionaryofAccountsandBalances = dict()
# Loop over the list and parse each line
for line in LinesoftheFileIJustRead:
# Split the line into pieces.
# By default .split uses whitespace.
splitline = line.split()
# Grab all of our values.
account = splitline[0]
addorsubtract = splitline[1]
amount = splitline[2]
# Add value.
if addorsubtract == '<':
DictionaryofAccountsandBalances[account] = DictionaryofAccountsandBalances.get(account, 500) + int(amount)
# Subtract value
elif addorsubtract == '>':
DictionaryofAccountsandBalances[account] = DictionaryofAccountsandBalances.get(account, 500) - int(amount)
# Print the total amounts
for key, value in DictionaryofAccountsandBalances.items():
print(key,value)