感謝您抽出寶貴時間接受采訪:我得到了一個模型,它必須填充3個txt文檔,每個文檔有40行。該命令應(yīng)打開每個取行,設(shè)置對象,保存它,然后在40范圍內(nèi)再次調(diào)用:我能夠調(diào)用它40次,盡管我40個正在使用相同的最后一行,我如何在txt文件上設(shè)置計數(shù)以在再次調(diào)用時轉(zhuǎn)到下一行?我應(yīng)該設(shè)置一個分割來獲取行作為列表嗎?并像列表索引一樣設(shè)置行?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 )...網(wǎng)址.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...藝術(shù)家.txtgordinho havaianoduke dumontMichael Jackson...
1 回答

慕桂英546537
TA貢獻1848條經(jīng)驗 獲得超10個贊
我想你可以一起打開所有3個文件,并用zip循環(huán)它。
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
提交
取消