DictReader,无引号,选项卡式文件
我有一个 csv 文件,如下所示: 请注意,没有引号,制表符 (\t) 是分隔符,标题和实际内容之间有一个空行。
Facility No Testing No Name Age
252 2351 Jackrabbit, Jazz 15
345 257 Aardvark, Ethel 41
我想我已经尝试了几乎所有可能的想法和参数的组合,
f = open('/tmp/test', 'r')
csvFile = f.read()
reader = csv.DictReader(csvFile, delimiter='\t', quoting=csv.QUOTE_NONE)
print reader.fieldnames
打印的结果是:
['F']
如何将其转换为我可以解析并放入数据库的内容? 把它编入字典会很有帮助。
I have a csv file that looks like this:
Please note, there are no quotes, a tab (\t) is the delimiter, and there is a blank line between the header and the actual content.
Facility No Testing No Name Age
252 2351 Jackrabbit, Jazz 15
345 257 Aardvark, Ethel 41
I think I've tried nearly every possible combination of ideas and parameters
f = open('/tmp/test', 'r')
csvFile = f.read()
reader = csv.DictReader(csvFile, delimiter='\t', quoting=csv.QUOTE_NONE)
print reader.fieldnames
the result of the print is:
['F']
How can I get this into something I can parse to put into a database?
Getting it into a dictionary would be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
csvFile
是什么?它是代表以“F”开头的文件名的字符串吗?csv.DictReader
需要一个打开的文件对象,而不是文件名。尝试:
编辑
如果您的
csvFile
是包含整个数据的字符串,则必须将其转换为StringIO
(因为csv
只能访问类似文件的对象,不能访问字符串)。尝试:
或者,如果您编辑的问题打开并读取文件:
这对我有用。
What is your
csvFile
? Is it a string representing your filename starting with 'F'?csv.DictReader
needs an opened file object, not a filename.Try:
EDIT
If your
csvFile
is a string containing the whole data, you will have to convert it into aStringIO
(becausecsv
can access only file-like objects, not strings).Try:
Or, if your edited question opens and reads a file:
This works for me.
这可能对你有用,至少作为一个开始:
this might work for you, at least as a start:
从评论中我了解到您通过
获取数据urllib2
。response
是一个类似文件的对象;您可以将其直接传递给csv.DictReader
:From the comments I understand that you get your data via
urllib2
.response
is a file-like object; you could pass it directly tocsv.DictReader
: