Python的QUOTE_NONNUMERIC导入CSV时不按预期工作

5 投票
1 回答
15666 浏览
提问于 2025-04-18 00:03

我搞不明白这个问题,可能是我盯着同样的东西太久了,看得有点晕...

我在一个CSV文件里有这样的行:

""BIN"",""Afg"",""SONIC/SONIC JET/"",1,8.9095,""Due to the dynamic nature of the exemptions granted to many operators, the Contract Price does not reflect V.A.T. / G.S.T., Mineral Oil Taxes, Federal Excise Taxes or other taxes to which an operator may be exempt.  Please contact your salesperson or World Fuel Services if you require assistance in generating a fuel price estimate."",""N/A"",""01-NOV-2013"

我想用这样的方式导入:

data = csv.DictReader(open(newdatafile), delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
data.fieldnames = [
    'iata', 'country', 'fbo', 'quantity', 'price', 'remarks', 'special', 'validdate'
]

for row in data:
    fuelentry = FuelPriceImport()
    fuelentry.iata = row['iata']
    fuelentry.fbo = row['fbo']
    fuelentry.min_quantity = row['quantity']
    fuelentry.net_price_liter = row['price']
    fuelentry.remarks = row['remarks']
    fuelentry.save()

当我运行这段代码时,它总是会报这个错:

could not convert string to float: the Contract Price does not reflect V.A.T. / G.S.T.

这个错误显然是在双引号字符串中的逗号后面出现的。

难道 QUOTE_NONNUMERIC 不应该正好避免这种情况吗?因为整个文本都是在双引号里的啊?

1 个回答

4

你的输入格式使用了双引号,这在CSV中相当于对引号进行转义。

你需要把双引号替换成单引号;你可以使用一个包装生成器来实时完成这个操作:

def undoublequotes(fobject):
    for line in fobject:
        yield line.replace('""', '"')

这假设列中的数据本身不包含双引号。

演示:

>>> import csv
>>> from pprint import pprint
>>> def undoublequotes(fobject):
...     for line in fobject:
...         yield line.replace('""', '"')
... 
>>> sample = '''\
... ""BIN"",""Afg"",""SONIC/SONIC JET/"",1,8.9095,""Due to the dynamic nature of the exemptions granted to many operators, the Contract Price does not reflect V.A.T. / G.S.T., Mineral Oil Taxes, Federal Excise Taxes or other taxes to which an operator may be exempt.  Please contact your salesperson or World Fuel Services if you require assistance in generating a fuel price estimate."",""N/A"",""01-NOV-2013"
... '''
>>> reader = csv.reader(undoublequotes(sample.splitlines(True)),
...                     quoting=csv.QUOTE_NONNUMERIC)
>>> pprint(next(reader))
['BIN',
 'Afg',
 'SONIC/SONIC JET/',
 1.0,
 8.9095,
 'Due to the dynamic nature of the exemptions granted to many operators, the Contract Price does not reflect V.A.T. / G.S.T., Mineral Oil Taxes, Federal Excise Taxes or other taxes to which an operator may be exempt.  Please contact your salesperson or World Fuel Services if you require assistance in generating a fuel price estimate.',
 'N/A',
 '01-NOV-2013']

撰写回答