Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: read CSV row by row and create a file per row

Basically I want to read my CSV and create one text file per row.
My CSV content is : Grenouille,1139,287,252,164,2017-03-04-21_35_19.jpg,1920,1080

I’ve done the following code:

import sys
import csv

with open('labels_grenouilles.csv', newline='') as csvfile:
    spamreader = list(csv.reader(csvfile, delimiter=' ', quotechar='|'))
    for row in spamreader:
        f = open(str(spamreader[5]) + ".txt", "a")
        f.write(str(spamreader[0]) + " " + str(spamreader[1]) + " " + str(spamreader[2]) + " " + str(spamreader[3]) + " " + str(spamreader[4]))
        f.close()

but instead of creating each time a new file it creates something like that :
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I missing ?

>Solution :

I see you’re using the for loop for each element of spamreader. In this case, your spamreader is a list, so if you use spamreader[5] to create a file you’ll get the same value everytime, since you’re using the 6th element of the list everytime in open().

Also using append in (open(spamreader[5], "a") this will create the file if it doesn’t exist or will simply add at the end of its content if it exists.

So, in conclusion, you’re opening the same file everytime because you’re using spamreader[5] in the for loop, and that’s the same value everytime.

My guess is that you want to use row in open() instead of spamreader

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading