How to apply recursive action to csv.Dictreader

Asked

Viewed 73 times

0

Hello, I created the following code but it only applies the function of creating the txt file using the last record of the CSV table, as I can do for it to create a file for each record of this table?

import csv
import os
with open('lista.csv') as listacsv:
leitor = csv.DictReader(listacsv)
for row in leitor:
    a = row['nome']
    b = row['empresa']

os.mknod("{}_{}.txt".format(a,b))

Follow the example CSV file:

nome,empresa,logo
Diego Rocha,Espaço Rocha,espacorocha.png
Adiana Bonfim,Bonfim Select,bonfim.png
Cris Matarazzo,Spazio Odontologia,spazio.png
  • Each file with a line: Diego Rocha,Espaço Rocha,espacorocha.png in an archive, in another archive Adiana Bonfim,Bonfim Select,bonfim.png etc.. Is that it? And the name of the archives?

1 answer

0

You came very close to solving the problem, however, lacked attention in relation to indentation. In Python this is crucial and delimits code blocks.

Follows a solution:

import csv
import os

with open('lista.csv') as listacsv:
    leitor = csv.DictReader(listacsv)
    for row in leitor:
        a = row['nome']
        b = row['empresa']
        nome = "{}_{}.txt".format(a,b).replace(" ","_")
        os.mknod(nome);

Archivos Gravados:

Adiana_Bonfim_Bonfim_Select.txt
Cris_Matarazzo_Spazio_Odontologia.txt
Diego_Rocha_Espaço_Rocha.txt
  • Friend, you have no idea how much you helped me with this information. thank you very much for your help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.