I have been trying to figure out how to take a list and use it to create a new column in my csv file. The idea is that I have a cvs file, I've taken the last item of each row to create a list, shuffled it and then I need to add it to the end of the file.
Some issues I ran into but 'think' I have fixed are: Python won't append a list of strings so I converted to int. Removing the column header and adding it back in.
What I have so far is:
def fun():
import csv
import random
f = open('CSVFUN.csv')
csv_f = csv.reader(f)
ISI = []
for line in csv_f:
ISI.append(line[4])
ISI = ISI[1:]
random.shuffle(ISI)
delay = [int(i) for i in ISI]
print(delay)
with open('CSVFUN.csv','r') as csvinput:
with open('CSVOUTPUT.csv','w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
for row in reader:
if row[0] == 'practicesentence':
writer.writerow(row+['FINALaudioDelay'])
else:
for i in delay:
writer.writerow(row+[delay[i]])
I think the issue I am having now is that my final else statement is iterating through my list of delay and adding each element of the list to each element in a row. So item 1 is getting 8 delays, item 2 gets 8 delays, and so on.
What I want is for item 1 to go with the first delay, item 2 with the second delay and so on.
I feel like I'm making some sort of stupid mistake but I just can't figure out what it is....
If you want to access the ith element of
delay
, then your code is correct. However, since you sayfor i in delay
,i
is already an element ofdelay
. Try changing outdelay[i]
for justi
in the last line. An example is belowThat will return:
However, if you do this:
This won't work because
list
only has elements with indices 0 and 1, not 4 and 5.