感谢您抽出宝贵时间接受采访:我得到了一个模型,它必须填充3个txt文档,每个文档有40行。该命令应打开每个取行,设置对象,保存它,然后在40范围内再次调用:我能够调用它40次,尽管我40个正在使用相同的最后一行,我如何在txt文件上设置计数以在再次调用时转到下一行?我应该设置一个分割来获取行作为列表吗?并像列表索引一样设置行?list[counter]models.py:class MP4 (models.Model): nome = models.CharField(blank=True, max_length=100) url = models.URLField(blank=True, max_length=300) imagem = models.ImageField(blank=True, upload_to='') artista = models.CharField(blank=True, max_length=100, default='Unknown')seeder.py(命令):class Command(BaseCommand): file_name = ['nome.txt', 'artista.txt', 'url.txt'] @classmethod def handle(cls, *args, **kwargs): counter = 0 for row in range(40): counter += 1 with open(cls.file_name[0]) as file: for linha in file: nome = linha with open(cls.file_name[1]) as file: for linha in file: artista = linha with open(cls.file_name[2]) as file: for linha in file: url = linha row = MP4( nome=nome, url=url, artista=artista, id=MP4.objects.latest('id').id + 1 ) row.save()名词.txt:Somewhere over the Rainbowocean driveMichael Jackson - Billie Jean ( cover by J.Fla )...网址.txt:https://www.youtube.com/watch?v=V1bFr2SWP1I&list=RDV1bFr2SWP1I&start_radio=1https://www.youtube.com/watch?v=KDxJlW6cxRk&list=RDVHoT4N43jK8&index=19https://www.youtube.com/watch?v=J1AdPY73qxo...艺术家.txtgordinho havaianoduke dumontMichael Jackson...
1 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
我想你可以一起打开所有3个文件,并用zip循环它。
file_name = ['nome.txt', 'artista.txt', 'url.txt']
with open(file_name[0]) as file1, open(file_name[1]) as file2, open(file_name[2]) as file3:
for data in zip(file1, file2, file3):
nome, artista, url = data
row = MP4(
nome=nome,
url=url,
artista=artista,
id=MP4.objects.latest('id').id + 1
)
row.save()
添加回答
举报
0/150
提交
取消