Python:使用csv modu有效读取文件

2024-10-02 10:32:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我们想阅读这个文件并创建一个字典,其中包含每个列的名称(作为键)和总计(作为值)。因此,在这种情况下,我们将得到:

^{pr2}$

所以我写了这段代码,它显然运行得很好,但我并不满意,我想知道是否有人知道更好或更高效/优雅的方法来实现这一点。因为这里有太多的行: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()

非常感谢您的回答:)


Tags: 文件csvaswithupdateopenintrow
3条回答

最后一个操作栏是空的:

#!/usr/bin/python

import csv
import numpy

with open("file.csv") as f:
    reader = csv.reader(f)
    headers = next(reader)

    sums = reduce(numpy.add, [map(int,x) for x in reader], [0]*len(headers))
    for name, total in zip(headers,sums):
        print("{}'s total is {}".format(name,total))

不确定你是否可以使用熊猫,但你可以得到你的口述如下:

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

给出:

^{pr2}$

使用顶行来计算列标题是什么。根据标题初始化汇总字典。在

import csv

with open("file.csv") as f:
  reader = csv.reader(f)

  titles = next(reader)
  while titles[-1] == '':
    titles.pop()
  num_titles = len(titles)      
  totals = { title: 0 for title in titles }

  for row in reader:
    for i in range(num_titles):
      totals[titles[i]] += int(row[i])

print(totals)

让我补充一下,您不必关闭with块之后的文件。with的全部意义在于它负责关闭文件。在

另外,请允许我指出,您发布的数据似乎有四列:

^{pr2}$

所以我才这么做:

  while titles[-1] == '':
    titles.pop()

相关问题 更多 >

    热门问题