带有Python引号的csv导入\u非数字不能按预期工作

2024-04-25 04:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想不出来,也许我是因为长时间看同样的东西而瞎了眼。。。

我在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完全避免这一点吗,因为整个文本都在双引号内?


Tags: thetodatanotpricequantityrowcontract
1条回答
网友
1楼 · 发布于 2024-04-25 04:23:40

您的输入格式使用double引号,这相当于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']

相关问题 更多 >