我是一个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}
试试这个:
第一行输入的输出(请记住字典是无序的):
^{pr2}$不同的软件系统称之为CSV的东西有很多不同。幸运的是,Python优秀的CSV模块非常擅长处理这些细节,因此您不需要手动处理这些事情。在
让我强调一下@metaperture的回答中使用的一些东西,但没有解释:通过自动检测方言,您可以避免阅读Python中CSV文件的所有猜测。一旦你把那部分钉好,就不会再有什么问题了。在
我给你举个简单的例子:
当您这样做时:
你要删除所有的新行,这是怎么做到的csv.excel文件方言检测新行。因为文件只有一行,所以只返回一次。在
此外,您还可以:
^{pr2}$在第一次迭代后终止for循环。在
关于为什么它们是空的,默认的restval是None(参见http://docs.python.org/3.2/library/csv.html),因此键可能不匹配。尝试不包括fieldnames参数,您可能会看到您在这个方言中的键是沿着“col2”、“col3”或类似的行。在
我用一个可爱的小包装纸:
用法示例:
相关问题 更多 >
编程相关推荐