Fun Questions...

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: May 2009
Posts: 3
Reputation: aparadox is an unknown quantity at this point 
Solved Threads: 0
aparadox aparadox is offline Offline
Newbie Poster

Fun Questions...

 
0
  #1
May 22nd, 2009
I'm kinda new to python, it really reminds me of Qbasic =\ ANYway lol.
I'm looking to do something extra in a class I'm taking. We were to make a budget program. That wasn't the hard part, what im looking to do is be able to save each entry of the budget as a unique entry in a file (text, CSV, etc) but i really dont know how to go about it.

an example would be:
loop = 0
while loop == 0:
expenseName = raw_input('What was the name of the expense? ')
expenseValue = int(raw_input('What was the value of the expense?')
choice = raw_input('Would you like to add another expense?')
if choice.....

now what i want to be able to do is save each of these as a single entry and then have the ability to edit them later. with a delete function. so it would end up being either in this script itself or exported to the said file. either way would be fine.

Im sure this is a newbie question but i don't know where to start with it. Any help would be amazing.
Last edited by aparadox; May 22nd, 2009 at 5:22 am.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: Fun Questions...

 
0
  #2
May 22nd, 2009
What's the problem here? Writing to a file or writing a unique value?
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Feb 2007
Posts: 77
Reputation: aot is an unknown quantity at this point 
Solved Threads: 1
aot's Avatar
aot aot is offline Offline
Junior Poster in Training

Re: Fun Questions...

 
0
  #3
May 22nd, 2009
Here's how I write to a file:

  1. import tempfile
  2.  
  3. # The path for storing any files with randomly generated (temp) names.
  4. path = 'data'
  5. tempfile.tempdir = path
  6.  
  7. # Generates a random filename not already in use.
  8. filename = tempfile.mktemp()
  9.  
  10. # Writes the given text to the file.
  11. def write(text=""):
  12. fileHandle = open(filename, 'a')
  13. fileHandle.write(text)
  14. fileHandle.close()

Note that the 'a' stands for 'append' -- this means adding on to the bottom of the file, and can be replaced with 'w' if you want to overwrite whatever is there. Also, 'r' stands for 'read' (only).

Of course, if you want, you can name the file whatever you like instead of generating a random name for it. I personally don't know anything about deleting within a file once you've written to it, although I know it's possible.

Also, if you're looking to store something that you will later want to use or change, consider pickling. When you pickle a python object (like a list), it makes a specially coded file so that any other python program can then unpickle it and treat it as a list again.

  1. import pickle
  2.  
  3. # Pickles a python object (e.g. a dictionary).
  4. def p(obj):
  5. fileHandle = open(filename, 'a')
  6. pickle.dump(obj, fileHandle)
  7. fileHandle.close()
  8.  
  9. sourceFolder = 'data'
  10.  
  11. # Gets data out of a pickled file.
  12. def unpickle(filename):
  13. file = sourceFolder + '/' + filename
  14.  
  15. fileHandle = open(file, 'r')
  16. data = pickle.load(fileHandle)
  17. fileHandle.close()
  18.  
  19. return data
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 3
Reputation: aparadox is an unknown quantity at this point 
Solved Threads: 0
aparadox aparadox is offline Offline
Newbie Poster

Re: Fun Questions...

 
0
  #4
May 22nd, 2009
Originally Posted by iamthwee View Post
What's the problem here? Writing to a file or writing a unique value?
Well the problem is either/or. I would like to write a unique variable for each answer, that seems to be the easiest way to manipulate the variables later.

Aot, im not sure that is the best way to go, i've used pickling b4 but couldnt seem to keep the data in order.
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 128
Reputation: slate is an unknown quantity at this point 
Solved Threads: 31
slate slate is offline Offline
Junior Poster

Re: Fun Questions...

 
1
  #5
May 22nd, 2009
Well, if you want the hard part...

Coming from a financial background I can assure you, that saving entries into a csv file permanently is a a bad idea. Unless the only purpose for this file is to import it to something more robust.

Deleting transactions looks like a bad idea, too. In bigger systems (more than one account, or more than one user) this is considered hacking and comes into play only, when something got really wrong. Consider storno...

If this is a basic budgeting program, then I personally would use:
1. Datastore layer
2. A data access layer
3. A business logic layer
4. A user interface layer

Datastore layer can be an any sql database, for the begin sqlite(included in python) will suffice. All other layer can be written in the begin by hand, and later you can try something more appropriate, like sqlalchemy for data access, or wxpython for UI.
The layering is very good, because you can separate concerns and can develop them (almost) separately.

But everything depends on, what you trying to accomplish.

So my imaginary budgeting program would have the functions:
  • Set initial balance
  • Input expenses/incomes
  • Report balance/transactions

I will not go into more detail, because my post will end up as a novel. But more questions are to be answered, like users, authorization, authentication, error checking, database design, fine tuning of requirements and so on. And with more answers come more questions

For learning purposes in the beginning every layer(except datastore) is only a class. In time these classes get bigger, and become modules...

I have written a very limited version of that. You can put in expenses, and get the balance. No error checking, no input validation, full of lazy shortcuts.

  1. import sqlite3
  2. class DataAccess():
  3. my_database="budget.db"
  4. def __init__(self):
  5. self.connection=sqlite3.connect(self.my_database)
  6. def create_database(self):
  7. self.connection.execute("create table account(id integer primary key, balance number);")
  8. self.connection.execute("create table transact(id integer primary key, narrativ text, amount number);")
  9. self.connection.execute("insert into account(balance) values(0);")
  10. self.connection.commit()
  11. def input_transaction(self, amount, narrativ):
  12. sqlstr="insert into transact (narrativ, amount) values(\"%s\",%s); " % (narrativ,amount)
  13. self.connection.execute(sqlstr)
  14. self.connection.execute("update account set balance=balance+%s; " % (amount))
  15. self.connection.commit()
  16. def get_balance(self):
  17. cu=self.connection.cursor()
  18. cu.execute("select * from account;")
  19. return cu.fetchall()
  20.  
  21. class BussinesLogic():
  22. def __init__(self):
  23. self.database=DataAccess()
  24. def report_balance(self):
  25. return self.database.get_balance()[0][1]
  26. def input_expense(self,expense, narrativ):
  27. self.database.input_transaction(-expense,narrativ)
  28. def create_database(self):
  29. self.database.create_database()
  30.  
  31.  
  32. import sys
  33. class UserInterface():
  34. def __init__(self, bl):
  35. self.bl=bl
  36. self.menu=dict()
  37. self.set_menu()
  38. def set_menu(self):
  39. self.menu[4]=("Report Balance",self.display_balance)
  40. self.menu[1]=("Input expense",self.get_expense)
  41. self.menu[2]=("Exit program",self.exit)
  42. self.menu[3]=("Create_database (budget.db)",self.bl.create_database)
  43. def display_balance(self):
  44. print ("your balance is: %s"%self.bl.report_balance())
  45. def get_expense(self):
  46. print("please input the data")
  47. amount=int(raw_input("amount:"))
  48. narrativ=raw_input("narrativ:")
  49. self.bl.input_expense(amount,narrativ)
  50. def exit(self):
  51. print ("Goodbye")
  52. sys.exit(0)
  53. def display_menu(self):
  54. print ("Personal Budgeting")
  55. print ("Please choose a function!")
  56. for k,v in self.menu.iteritems():
  57. print k,v[0]
  58. def main(self):
  59. choice=-1
  60. while True:
  61. self.display_menu()
  62. choice=int(raw_input("?:"))
  63. self.menu[choice][1]()
  64.  
  65. if __name__=="__main__":
  66. BL=BussinesLogic()
  67. UI=UserInterface(BL)
  68. UI.main()
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 3
Reputation: aparadox is an unknown quantity at this point 
Solved Threads: 0
aparadox aparadox is offline Offline
Newbie Poster

Re: Fun Questions...

 
0
  #6
May 22nd, 2009
As far as security or connections is concerned it doesn't matter really. i understand that this really isn't the way to design the code for a actual real world use. I guess my main question is how to do this...
addExpense():
nameExpense = raw_input('What is the name of the expense')
valueExpense = int(raw_input('What is the value of the expense')
entry = nameExpense, valueExpense

now what i want to be able to do is have each 'entry' as a indexed number, i.e. the first would be 001, Rent, $500 so in a text file or a CSV file i would be able to list 001 then have the option of deleting that option. such as:
def delExpense():
delE = int(raw_input('What expense would you like to delete? ')
del delE


is it possible to make a indexed variable like, user runs addExpense() each entry would be indexed in the same way without using a external file? this is a weird question i understand im just looking at options for this case really, not to say security doesn't matter to me but this is just for a 1 user program that wouldn't require access or save "real" budget information.
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 128
Reputation: slate is an unknown quantity at this point 
Solved Threads: 31
slate slate is offline Offline
Junior Poster

Re: Fun Questions...

 
0
  #7
May 22nd, 2009
I am not sure I understand your "weird" question.

You either put the index into the csv file, or use some natural index, ie the line count.

In both cases you need to get the last index from the file.
This can be done, when the application is started and then internally keep track of it.

However deleting a line from a file without rewriting the data "under" the deleting line cannot be done, I think. That does not sound efficient. The other way is, to delete the line logically, and new entries can use this dead space. This is the beginning of database.

If the data is read into the memory, than practically everything is possible. Except using del Del is a language statement reserved for forcing garbage collection.

But you you can use a delEntry function, which does that, and uses your desired del statement

  1.  
  2. def delEntry(index):
  3. fname="budget.csv"
  4. entries=open(fname).readlines()
  5. del entries[index]
  6. fo=open("budget.csv","w")
  7. fo.writelines(entries)
  8. fo.close()
  9.  
  10. def delExpense():
  11. delE = int(raw_input('What expense would you like to delete? '))
  12. delEntry(delE)
  13. delExpense()
Last edited by slate; May 22nd, 2009 at 4:40 pm.
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 35
Reputation: comprookie2000 is an unknown quantity at this point 
Solved Threads: 3
comprookie2000's Avatar
comprookie2000 comprookie2000 is offline Offline
Light Poster

Re: Fun Questions...

 
0
  #8
May 22nd, 2009
Thanks Slate for the exercise, lot of fun for a new python student.
I added a menu item to add funds, that is fine.
I added a menu item to report all the transactions, I can not figure out how to pull the info from the database to display it correctly.
  1. def get_transactions(self):
  2. ct=self.connection.cursor()
  3. ct.execute("select * from transact;")
  4. return ct.fetchall()
  5.  
  6. def report_transactions(self):
  7. return self.database.get_transactions()
  8.  
  9. def display_transactions(self):
  10. print "Your tranaction History is:",self.bl.report_transactions()
  11.  
  12. self.menu[5]=("Transaction History",self.display_transactions)
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 35
Reputation: comprookie2000 is an unknown quantity at this point 
Solved Threads: 3
comprookie2000's Avatar
comprookie2000 comprookie2000 is offline Offline
Light Poster

Re: Fun Questions...

 
0
  #9
May 22nd, 2009
Forgot the results;

Your tranaction History is: [(1, u'Food', -100), (2, u'Deposit', -200), (3, u'Deposit', 500)]
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum


Views: 402 | Replies: 8
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC