繁体   English   中英

python csv DictReader 导入名称中带有斜线的日期的列

[英]python csv DictReader Import columns that have dates with slashes in the names

我有一个 csv 文件,其中列名中的日期带有斜线 - 2020 年 4 月 10 日。 它可以使用 Python csv.reader 正常导入,但该文件每天都会添加一列。 我无法控制 csv 文件。

使用 csv.reader 我必须猜测列号。 我想用 csv.DictReader 对它进行 map 它,然后插入日期以对列求和。 使用列名中的斜杠,我得到

密钥错误:“2020 年 4 月 10 日”

我试过 escaping 它带有 \、双引号和刻度。 我已经搜索并尝试了一段时间。 我知道这里有几十个可以通过几次击键来回答这个问题。 提前致谢。

在编辑中添加了 csv 缩写逗号

Lat,    Long_,  place_name,             1/22/2020,  1/23/2020
-14.271,    -170.132,   American Samoa, 0,           0
13.4443,    144.7937,   Guam,            1,            0   

我可以通过以下方式很好地导入它:

import csv
 dir = 'home/me/'
 file = 'time_series.csv'
 with open(dir + file) as file:
   reader = csv.reader(file)
   for row in reader:
       print(row[0], row[1], row[2], row[3], row[3])

**编辑:**这是上面的 output:

me@hills:~/tmp/c19$ python cSum.py
Lat  Long_  place_name  1/22/2020  1/23/2020
-14.271  -170.132  American Samoa  0  0
13.4443  144.7937  Guam  0  0
15.0979  145.6739  Northern Mariana Islands  0  0
18.2208  -66.5901  Puerto Rico  0  0

我要完成的工作:

import csv
dir = 'home/me/'
file = 'time_series.csv'
#cr = csv.reader(open(dir + file))
cr = csv.DictReader(open(dir + file))
next(cr) #  skip the header

total = 0
for row in cr:
total += int(row['1/22/2020'])

print (total)

从上方编辑output:

me@hills:~/tmp/c19$ python c1.py
Traceback (most recent call last):
File "c1.py", line 10, in <module>
total += int(row['1/22/2020'])
KeyError: '1/22/2020'

不用担心目录结构——被混淆了。

我强烈建议您使用 DictReader 而不是 reader 来使用它。 此外,仅读取有多少行只需使用reader.line_num ,它就会为您提供有多少行。 这是使用 DictReader 解析 CSV 文件的示例:)。

import csv


def main():
    file_path = r"yourfilepath"

    # Opening the file for reading.
    with open(file_path, "r") as csv_file:
        reader = csv.DictReader(csv_file)

        # Getting the csv data as dictionary.
        values = reader.next()

    # Printing the key and its values.
    for key, value in values.items():
        print "{}: {}".format(key, value)


if __name__ == "__main__":
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM