Python的csv DictReader对于字段值返回“None”;有什么想法吗?

2024-09-27 22:23:41 发布

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

我是一个noob程序员,在用pythonscsv模块解析csv文件时遇到了一个问题。问题是,我的输出显示行中的字段值对于除第一个字段之外的所有字段都是“无”。在

下面是我试图解析的丑陋csv文件中的第一行(其余行采用相同的格式):

0,213726,NORTH FORK SLATE CREEK,CAMPGROUND,North Fork Slate Creek Campground | Idaho |      Public Lands Information Center | Recreation Search, http://www.publiclands.org/explore/site.php?plicstate=ID&id=2268,NA,NA,NA,NA,(208)839-2211,"Nez Perce National Forest  Operating Days: 305<br>Total Capacity: 25<br>

5 campsites at the confluence of Slate Creek and its North Fork. A number of trails form loops in the area. These are open to most traffic, including trail bikes.","From Slate Creek, go 8 miles east on Forest Road 354.",NA,http://www.publiclands.org/explore/reg_nat_forest.php?region=7&forest_name=Nez%20Perce%20National%20Forest,NA,NA,NA,45.6,-116.1,NA,N,0,1103,2058

这是我写的用来解析csv文件的代码(它不能正常工作!)公司名称:

^{pr2}$

这是输出。上面说除了第一个字段外,所有字段都是空白的,我不知道为什么!如有任何建议,将不胜感激。在

my first row was {'col14': None, 'col15': None, 'col16': None, 
'col17': None, 'col10': None, 'col11': None, 'col12': None, 
'col13': None, 'col18': None, 'col19': None, 'col2': None, 'col8': None, 
'col9': None, 'col6': None, 'col7': None, 'col4': None, 'col5': None, 
'col3': None, 'col1': '0', 'col25': None, 'col24': None, 
'col21': None, 'col20': None, 'col23': None, 'col22': None}

Tags: 文件csvorgnonehttpwwwforkexplore
3条回答

试试这个:

#!/usr/bin/env python

import csv

my_fieldnames = ['col' + str(i) for i in range(1,26)]

with open('input.csv', 'rb') as csvfile:
    my_reader = csv.DictReader(csvfile, fieldnames=my_fieldnames,
                               delimiter=',', dialect=csv.excel,
                               quoting=csv.QUOTE_NONE)

    for row in my_reader:
        for k,v in row.iteritems():
            print k, v

第一行输入的输出(请记住字典是无序的):

^{pr2}$

不同的软件系统称之为CSV的东西有很多不同。幸运的是,Python优秀的CSV模块非常擅长处理这些细节,因此您不需要手动处理这些事情。在

让我强调一下@metaperture的回答中使用的一些东西,但没有解释:通过自动检测方言,您可以避免阅读Python中CSV文件的所有猜测。一旦你把那部分钉好,就不会再有什么问题了。在

我给你举个简单的例子:

    import csv

    with open(filename, 'rb') as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(10024))
        csvfile.seek(0)
        qreader = csv.reader(csvfile, dialect)
        cnt = 0
        for item in qreader:
            if cnt >0:
                #process your data
            else:
                #the header of the csv file (field names)    
            cnt = cnt + 1

当您这样做时:

f_handler = open(f_path, 'rU').read().replace('\n',' ')

你要删除所有的新行,这是怎么做到的csv.excel文件方言检测新行。因为文件只有一行,所以只返回一次。在

此外,您还可以:

^{pr2}$

在第一次迭代后终止for循环。在

关于为什么它们是空的,默认的restval是None(参见http://docs.python.org/3.2/library/csv.html),因此键可能不匹配。尝试不包括fieldnames参数,您可能会看到您在这个方言中的键是沿着“col2”、“col3”或类似的行。在

我用一个可爱的小包装纸:

def iter_trim(dict_iter):
#return (dict(zip([k.strip(" \t\n\r") for k in row.keys()], [v.strip(" \t\n\r") for v in row.values()])) for row in dict_iter)
 for row in dict_iter:
    try:
        d =  dict(zip([k.strip(" \t\n\r") for k in row.keys()], [v.strip(" \t\n\r") for v in row.values()]))
        yield d
    except:
        print "row error:"
        print row

用法示例:

def csv_iter(filename):
    csv_fp = open(filename)
    guess_dialect = csv.Sniffer().sniff(csv_fp.read(16384))
    csv_fp.seek(0)
    csv_reader = csv.DictReader(csv_fp,dialect=guess_dialect)
    return iter_trim(csv_reader)
for row in csv_iter("some-file.csv"):
    # do something...
    print row

相关问题 更多 >

    热门问题