获取TypeError:字节索引必须是整数或切片,而不是str

时间:2019-08-31 18:41:05

标签: python python-3.x postgresql django-2.2

我有一个名为Branches的模型表,该表将从在线托管的CSV文件中自动归档。但是,我不断收到错误消息

我该如何解决? 谢谢

from django.db import models

class Branches(models.Model):

    ifsc       = models.CharField(max_length=1009)
    bank_id    = models.IntegerField()
    branch     = models.CharField(max_length=1009)
    address    = models.CharField(max_length=1500)
    city       = models.CharField(max_length=1999)
    district   = models.CharField(max_length=1999)
    state      = models.CharField(max_length=1000)
    bank_name  = models.CharField(max_length=1000)


    def __str__(self):
        return self.branch

from urllib.request import urlopen, Request
from io import StringIO
import csv

for row in urlopen('https://raw.githubusercontent.com/snarayanank2/indian_banks/dc7ac64137ecf24bfc564f3d6151331215cf4783/bank_branches.csv'):
    Branches.objects.create(ifsc=row['ifsc'], bank_id=row['bank_id'], branch=row['branch'], address=row['address'], city=row['city'], district=row['district'], state=row['state'], bank_name=row['bank_name'])

1 个答案:

答案 0 :(得分:0)

在Daniel Nudelmans评论的基础上,这是将split与当前代码一起使用的方式:

for row in urlopen('https://raw.githubusercontent.com/snarayanank2/...'):
    row = row.split(",")
    # row is now a list containing all the values from the row
    Branches.objects.create(ifsc=row[0], bank_id=row[1], branch=row[2], address=row[3], city=row[4], district=row[5], state=row[6], bank_name=row[7])

请记住,如果CSV具有标头(例如“ ifsc”,“ bank_id”等作为第一行),则在for循环的第一次迭代中,row将是标头的名称。