Now it’s time to put the reading and writing functions together. def write_expenses():Įxpense_writer = csv.writer(f, delimiter=",")ĭate = input("What date was the expense incurred? ")Ĭategory = input("What category is the expense for? ")Ĭost = input("How much money did you spend? ")Įxpense_writer.writerow()Įnd = input("If you are done inputting expenses, type \"end\" ")į.close() Seeing and Adding to Your Expenses If they are, then we set our reporting variable to False to end the while loop. Once we write the data in, we ask the user if they are done reporting. We write this data that the user input into the expense tracker. While we are reporting, we ask the user to input the date, category, and cost. To do this, we start with a reporting variable that we set to True and then open up the expenses file in append mode and create a CSV writer with it. Our write_expenses function executes a while loop while we are reporting expenses. Now that we’ve created a function to read from our expense tracker, let’s create a function to write to it. Print("No Expense Tracker File Exists Yet") Writing to Your Python Expense Tracker # expenses come in the columns of date (0), category (1), price (2) import csvĬsv_reader = csv.reader(f, delimiter=",") If there is no expenses.csv file, we simply print out that the file doesn’t exist and move on. We show the user that on a certain date, they spend the cost on the category. This column format has to be followed for both the expense reader and writer. Notice the comment there that denotes the way that the expenses are written. We use the CSV reader to add all the rows of the expense tracker to the list of expenses. Next, we declare an empty list that represents the expenses. This means we need to make sure that we run this program in the same folder that we have the program code and the CSV file.įirst, we try to open the expenses.csv file and create a CSV reader. We’re hard-coding in the name of our expense file. Our read_expenses function doesn’t need any parameters. First things first, we import the csv library. For this tutorial, I chose to start with reading expenses. We could start with a function to read from or write to the CSV file that we’re using to track our expenses. Reading Expenses from a CSV File in Python Summary of How to Build a Python Expense Trackerįind this project on GitHub. Reading Expenses from a CSV File in Python.By the end of this tutorial, you’ll have a Python expense tracking program that shows you your expenses and allows you to add to the tracker. This Python expense tracker will simply track your expenses in a CSV file. In this post, we’re going to build a simple expense tracker in Python for exercise. Expense tracking is a common task used in every industry.
0 Comments
Leave a Reply. |