读取csv文件中最后一行的第二列

时间:2019-07-11 23:11:55

标签: python python-3.x csv

我正在尝试创建一个点钞机,您可以在其中添加资金和取出资金,并只跟踪您的资金去向(这对我来说只是一个小项目,我知道有很多更好的应用程序都适合于此)。

我想在每次运行程序时显示当前余额,唯一的问题是如何读取csv文件的最后一行和其中的第二列。

这是我的csv文件布局:

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

我当前的代码是:

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} ")

我对编程很陌生,所以我不确定如何获取特定的列和行。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

不是超级快,但是:

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]

您打开文件,然后使用readlines()读回所有数据 进入列表。即,您在每一行的列表中都有一个项目。然后 访问最后一个元素-data[-1],然后将其拆分为一个列表 split(',')。您可能需要在逗号后使用空格,只是播放 关于它。最后,您从该列表中获取第二个元素。 请记住,python使用基于0的索引。

如果您有任何疑问,请告诉我。祝你好运。

编辑:已更新,每个@martineau的制表符分隔

答案 1 :(得分:0)

我认为使用pandas处理表/数据框更容易。您可以使用类似这样的内容:

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

答案 2 :(得分:0)

您可以通过更新对问题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