Python:使用 csv 模块有效读取文件

标签 python file csv text

我最近刚刚开始学习csv模块。假设我们有这个 CSV 文件:

John,Jeff,Judy,
21,19,32,
178,182,169,
85,74,57,

我们想要读取此文件并创建一个包含名称(作为键)和每列总计(作为值)的字典。所以在这种情况下我们最终会得到:

d = {"John" : 284, "Jeff" : 275, "Judy" : 258}

所以我编写了这段代码,它显然运行良好,但我对此不满意,并且想知道是否有人知道更好或更有效/优雅的方法来做到这一点。因为那里的行太多了:D(或者也许我们可以稍微概括一下 - 即我们不知道那里有多少个字段。)

d = {}
import csv
with open("file.csv") as f:
    readObject = csv.reader(f)

    totals0 = 0
    totals1 = 0
    totals2 = 0
    totals3 = 0

    currentRowTotal = 0
    for row in readObject:
        currentRowTotal += 1
        if currentRowTotal == 1:
            continue

        totals0 += int(row[0])
        totals1 += int(row[1])
        totals2 += int(row[2])
        if row[3] == "":
            totals3 += 0

f.close()

with open(filename) as f:
    readObject = csv.reader(f)
    currentRow = 0
    for row in readObject:   
        while currentRow <= 0:
            d.update({row[0] : totals0}) 
            d.update({row[1] : totals1}) 
            d.update({row[2] : totals2})
            d.update({row[3] : totals3}) 
            currentRow += 1
    return(d)
f.close()

非常感谢您的回答:)

最佳答案

不确定你是否可以使用 pandas,但你可以按如下方式获取你的字典:

import pandas as pd
df = pd.read_csv('data.csv')
print(dict(df.sum()))

给予:

{'Jeff': 275, 'Judy': 258, 'John': 284}

关于Python:使用 csv 模块有效读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139744/

相关文章:

python - 带有缺失/不完整标题或不规则列数的 read_csv

java - 带有列标题的 StatefulBeanToCsv

c++ - 来自带有分隔符的 std::getline 的段错误

python - 与Python `arcname`模块中的 `tarfile`选项相对应的tar选项是什么?

python - 将多个列表合并到python中的单个字典中

python - Python 有标准的 PTS 阅读器或解析器吗?

python - 如何 append JSON 文件?

python - 在 Django Rest Framework 中返回图片 url

python - 找到两个 DNA 字符串之间的汉明距离

c - 多线程共享文件的读访问: pthreads