1

I am trying to make a money counter whereby you can add money and remove money and just track where your money is going (this is just a mini project for me, I am aware there are much better apps suited for this).

I would like to present the current balance every time the program is run, my only problem is how I can read the last row in the csv file and the second column in it.

This is my csv file layout:

Date, Current Balance, Money In, Money Out, Reason, Other
10/04/1994, £205, £10, -, Birthday, -

My current code is:

with open("Logs.csv", "r") as f:
    for row[-1] in f:
        currentBalance = row[-1], row[-2]


def MainMenu():
    print(f"{bnum1} Welcome to your Money Logger! {bnum1}\n\
{bnum2} 1.         Money In           {bnum2}\n\
{bnum2} 2.         Money Out          {bnum2}\n\
{bnum3} ")

I'm quite new to programming so i'm not really sure how to go about fetching a specific column and row. Any help would be much appreciated.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

Not super fast, but:

with open('Logs.csv', 'r') as logs:
    data = logs.readlines()
    last_row = data[-1].split('\t') # Update for tab delimit.
    second_cell = last_row[1]

You open the file, then use readlines() to read all of the data back into a list. That is, you have an item in the list for each line. Then access the last element - data[-1], and split that into a list with split(','). You may need to use a space after the comma, just play about with it. Last, you grab the second element from that list. Remember python uses 0 based indexes.

Let me know if you have questions. Good luck.

Edit: Updated with tab delimit per @martineau

DasHund
  • 81
  • 4
  • So this is my current code after adding your code: codeshare.io/5QLp6q. The problem is, I'm getting a index error: line 14, in second_cell = last_row[1] IndexError: list index out of range. Any ideas how to fix this?, Thanks for everything – DeathResister Jul 12 '19 at 23:25
  • I suspect @martineau is correct. If you can show me what's in the line that fails, I can help. – DasHund Jul 13 '19 at 02:30
  • line 15 in your variation but in Martineau it's the same error but different line. – DeathResister Jul 15 '19 at 21:46
  • Updated with @martineau's comments. – DasHund Jul 16 '19 at 14:51
0

I think it is easier to use pandas to handle a table/dataframe. You could use something like:

import pandas as pd
df = pd.read_csv('Logs.csv')
print(df.iloc[:, 1]) # print the second column
print(df.iloc[1, :]) # print the second row
Shuo Han
  • 108
  • 4
  • Thanks for your response, I feel like pandas is quite a complicated module in general for beginners like me. But thanks again. – DeathResister Jul 12 '19 at 23:19
0

You can do it by using the update to my answer to the question AttributeError when trying to use seek() to get last row of csv file.

from collections import deque
import csv

def get_last_row(csv_filename):
    with open(csv_filename, 'r', newline='') as f:
        try:
            lastrow = deque(csv.reader(f, delimiter='\t'), 1)[0]
        except IndexError:  # Empty file.
            lastrow = None
        return lastrow


row = get_last_row("Logs.csv")
print(row[1])  # Print second column. -> £205
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Hmm... I'm getting an index error for this code: https://codeshare.io/anMZrV. line 30, in print(row[1]) # Print second column. -> £205 IndexError: list index out of range – DeathResister Jul 12 '19 at 23:30
  • DeathResister: Sounds like the last row doesn't have a second column. Put a `print(row)` before the `print(row[1])`and see what's in it. – martineau Jul 12 '19 at 23:34
  • It prints this out "['10/04/1994\t£205\t£10\t-\tBirthday\t-']" – DeathResister Jul 15 '19 at 21:37
  • @DeathResister: Oh...it's because your csv file is tab- not comma-delimited — which isn't obvious from the csv file layout posted in your question, See update to my answer. – martineau Jul 15 '19 at 22:13