读入CSV并捕获用于计算的值

uqjltbpv  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(105)

我需要逐行读取csv文件并进行一些计算。例如,假设我有一个名为test.csv的csv文件,下面有数据。我想逐行读取该文件并计算每个客户的利润(收入-支出)。

client,revenue,expenses
client_a,1000,450
client_b,2000,1200
client_c,1500,350

我在网上找了很多,但我不确定。我可以逐行读取文件或打印文件,但不确定是否需要为每个字段赋值。我假设我需要将它们声明为int,因为我正在进行计算。
我不想用清单。
下面是我必须读入文件并在屏幕上打印出来的内容。我知道我需要逐行遍历文件并进行计算。纠结于如何从csv文件中调用值以及如何忽略第一行。

inputfile = open('test.csv', "r")

print(inputfile.readline())
wecizke3

wecizke31#

csv模块中DictReader将根据csv文件中每一行创建字典它会将标题视为键,将其下一行视为值
赋值后,迭代inputfile,打印每对字典,并在转换为整数后对每个值执行计算

from csv import DictReader

inputfile = DictReader(open('test.csv'))
for row in inputfile:
    print(f"{row['client']} profit : {int(row['revenue']) - int(row['expenses'])}")

# client_a profit : 550
# client_b profit : 800
# client_c profit : 1150
n8ghc7c1

n8ghc7c12#

至少,你应该使用csv库。

import csv

with open("input.csv", "r") as file:
    mycsvfile = csv.reader(file, delimiter=",")
    
    for line, content in enumerate(mycsvfile):
        
        if line == 0:
            continue
        
        print("the client number {} is : {}".format(line, content[0]))
        
        print("the client number {} earns : {} $".format(line, content[1]))
        
        print("the client number {} spends {} $".format(line, content[2]))

输出将为

the client number 1 is : client_a
the client number 1 earns : 1000 $
the client number 1 spends 450 $
the client number 2 is : client_b
the client number 2 earns : 2000 $
the client number 2 spends 1200 $
the client number 3 is : client_c
the client number 3 earns : 1500 $
the client number 3 spends 350 $

相关问题