我有一个CSV文件,其中包含我想要使用Django Custom Management命令中的自定义命令导入的数据。我使用的是Python 2.7和Django 1.10。这是代码。
import csv
import argparse
from awards.models import Student, HomeRoom
from django.core.management.base import BaseCommand, CommandError
homeroom = 'HR 12C'
class Command(BaseCommand):
help = "Import students by homeroom."
def add_arguments(self, parser):
parser.add_argument('csvfile', nargs='+', type=argparse.FileType('r'))
def handle(self, *args, **options):
student_list = []
hr = HomeRoom.objects.get(name=homeroom)
with open(options['csvfile']) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
student_list.append(Student(name=row["Student Name"], studentidnum=row["School ID"], homeroom=hr))
是的,教室是硬编码的。我宁愿从文件名中取出该值(即HR 12C.csv'),但我不知道该怎么做。但这不是真正的问题。当我使用以下命令运行上面的代码时:python manage.py importcsv' awards / 12C.csv'我收到以下错误:
File "/home/ssidollars/dollars/awards/management/commands/importcsv.py", line 18, in handle
with open(options['csvfile']) as csvfile:
TypeError: coercing to Unicode: need string or buffer, list found
我不知道我做错了什么。似乎认为我已经将它列为一个列表,但是......我没有看到任何可能的列表。我有什么想法我做错了吗?
答案 0 :(得分:2)
如果您只传递一个参数,请将nargs='+'
更改为nargs='?'
以避免处理列表。
然后解析器返回的options['csvfile']
对象已经是TextIOWrapper
,无需再次打开它。
你可以用这种方式达到你想要的目的:
class Command(BaseCommand):
help = "Import students by homeroom."
def add_arguments(self, parser):
parser.add_argument('csvfile', nargs='?', type=argparse.FileType('r'))
def handle(self, *args, **options):
student_list = []
hr = HomeRoom.objects.get(name=homeroom)
with options['csvfile'] as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
student_list.append(Student(name=row["Student Name"], studentidnum=row["School ID"], homeroom=hr))