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 :
What am I missing ?
CodePudding user response:
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