尝试从python中的csv文件添加和 [英] Trying to add sums from a csv file in python

查看:123
本文介绍了尝试从python中的csv文件添加和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加csv文件的和。该程序是一个旅行预订系统的测试,文件读取如下:

I need to add sums of a csv file. The program is a test for a travel reservation system and the file reads like this:

availableSTART,reservations,cancellations,availableEND
20,1,0,18

我需要从可用的开始整数中减去预留,添加回取消(在这种情况下结果为0),然后打印输出,在这种情况下导致18.
到目前为止,我已打开CSV文件并打印它包含什么。
这里是我的代码这远。任何帮助将不胜感激。

I need to subtract reservations from the available start integer, then add back cancellations (Which in this case results to 0) and then print the output, which in this case results in 18. So far, I have opened the CSV file and printed what it contains. Here is my code this far. Any help would be appreciated!

import csv

with open ('transactions.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    print (readCSV)

    for row in readCSV:
        print(row)


推荐答案

读取CSV文件的一种方法是使用 csv.DictReader

One way to read a CSV file is using a csv.DictReader.

此对象可以迭代您的CSV文件并返回一个字典,其中的键是列名称,值是行值。
但是您需要将字符串值转换为整数:

This object can iterate your CSV file and return a dictionary which keys are columns names and values are row values. But you need to convert string values to integers:

>>> import io
>>> import csv

>>> with io.open('transactions.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         values = {k: int(v) for k, v in row.items()}
...         print(values)
...
{'availableEND': 18, 'reservations': 1, 'availableSTART': 20, 'cancellations': 0}

...

>>> with io.open('transactions.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         values = {k: int(v) for k, v in row.items()}
...         sums =  values['availableSTART'] + values['cancellations'] - values['reservations']
...         print(sums)
19

这篇关于尝试从python中的csv文件添加和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆