导入CSV脚本 - 使python 2.7兼容

时间:2015-11-05 11:30:00

标签: python django python-2.7 csv

我创建了以下脚本来将文件导入我的django模型。它工作正常,但只有在使用python 3.4。

如何更改此脚本以使其在2.7上运行?

谢谢,

错误:

Traceback (most recent call last):
  File "update_fromcsv.py", line 18, in <module>
    l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))
TypeError: 'errors' is an invalid keyword argument for this function

我的导入文件:

import sys, os
import django

sys.path.append('/srv/apps/stashdDB/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'stashdDB.settings'

django.setup()

import stashd.models as m




import csv

l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))

Gender_CHOICES = {
    'Male': 1,
    'Female': 2,
    'Unisex': 3,
}

Stock_CHOICES = {
    'in stock': 1,
    'low stock': 2,
    'out of stock': 3,
    'discountinued': 4
}

for i in l[1:]:
        cat = m.Category.objects.get_or_create(category_name = i[4])[0]
        prod = m.Product(
            name = i[0],
            link = i[1],
            description = i[6],
            brand = i[7],
            gender = Gender_CHOICES[i[8]] if i[8] in Gender_CHOICES else 3,
            store = m.Store.objects.get_or_create(store_name = i[2])[0]
            )
        prod.save()
        var = m.Variation(
            product = prod,
            variation = "default"
            )
        var.save()
        img = m.Image(
            variation = var,
            image = i[5]
            )
        img.save()
        size = m.Size(
            variation = var
            )
        size.save()
        price = m.Price(
            variation = var,
            price = float(i[3])
            )

等...

1 个答案:

答案 0 :(得分:0)

l = list(csv.reader(open('test_data.csv', 'rb')))