使用 Python 的 QUOTE_NONNUMERIC 导入 csv 无法按预期工作

nor*_*mic 5 python csv quoting double-quotes

我无法弄清楚这一点,也许我因为长期关注同样的东西而变得盲目......

我在 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"
Run Code Online (Sandbox Code Playgroud)

我正在尝试像这样导入:

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()
Run Code Online (Sandbox Code Playgroud)

当我运行这段代码时,它总是抱怨:

could not convert string to float: the Contract Price does not reflect V.A.T. / G.S.T.
Run Code Online (Sandbox Code Playgroud)

显然,它直接位于双引号字符串中的逗号之后。

QUOTE_NONNUMERIC由于整个文本都在双引号内,因此不应该完全避免这种情况吗?

Mar*_*ers 4

您的输入格式使用引号,这相当于转义引号的 CSV。

您必须将双引号替换为单引号;您可以使用包装器生成器即时执行此操作:

def undoublequotes(fobject):
    for line in fobject:
        yield line.replace('""', '"')
Run Code Online (Sandbox Code Playgroud)

这确实假设列数据本身不包含双引号。

演示:

>>> 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']
Run Code Online (Sandbox Code Playgroud)