DictReader,无报价,标签文件 [英] DictReader, No quotes, tabbed file

查看:210
本文介绍了DictReader,无报价,标签文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,如下所示:
请注意,没有引号,一个制表符(\t)是分隔符,在标题和实际内容之间有一个空白行。

 设施无测试否姓名年龄

252 2351 Jackrabbit,Jazz 15
345 257 Aardvark,Ethel 41

我想我已经尝试过几乎所有可能的想法和参数组合

  f = open('/ tmp / test','r')
csvFile = f.read b reader = csv.DictReader(csvFile,delimiter ='\t',quoting = csv.QUOTE_NONE)
print reader.fieldnames

打印结果是:

  ['F'] 

如何获得我可以解析放入数据库的东西?

解决方案

csvFile code>?是否是以F开头的字符串?



csv.DictReader 需要一个打开的文件对象,

 打开(csvFile, 'rb')as f:
reader = csv.DictReader(f,delimiter ='\t',quoting = csv.QUOTE_NONE)
print reader.fieldnames

EDIT



如果您的 csvFile 是一个包含整个数据的字符串,您必须将其转换为 StringIO (因为 csv 只能访问类文件对象,而不是字符串)。



尝试:

 来自cStringIO import StringIO 

#csvFile ='Facility No\tTesting No\tName\tAge\\\
\\\
252\t2351\tJackrabbit,Jazz \t15\\\
345\t257\tAardvark,Ethel\t41\\\
'
reader = csv.DictReader(StringIO(csvFile),delimiter ='\t',quoting = csv.QUOTE_NONE)
print reader.fieldnames

或者,如果您编辑的问题打开并读取文件: / p>

 以open('/ tmp / test','rb')as f:
reader = csv.DictReader f,delimiter ='\t',quoting = csv.QUOTE_NONE)
print reader.fieldnames

这适合我。


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.

解决方案

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:

with open(csvFile, 'rb') as f:
    reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    print reader.fieldnames

EDIT

If your csvFile is a string containing the whole data, you will have to convert it into a StringIO (because csv can access only file-like objects, not strings).

Try:

from cStringIO import StringIO

# csvFile = 'Facility No\tTesting No\tName\tAge\n\n252\t2351\tJackrabbit, Jazz\t15\n345\t257\tAardvark, Ethel\t41\n'
reader = csv.DictReader(StringIO(csvFile), delimiter='\t', quoting=csv.QUOTE_NONE)
print reader.fieldnames

Or, if your edited question opens and reads a file:

with open('/tmp/test', 'rb') as f:
    reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    print reader.fieldnames

This works for me.

这篇关于DictReader,无报价,标签文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆