creating a new column in a CSV file from a list

2019-08-14 16:43发布

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....

1条回答
smile是对你的礼貌
2楼-- · 2019-08-14 17:07

If you want to access the ith element of delay, then your code is correct. However, since you say for i in delay, i is already an element of delay. Try changing out delay[i] for just i in the last line. An example is below

list = [5, 4]
for i in list:
    print i

That will return:

5
4

However, if you do this:

list = [5, 4]
for i in list:
    print list[i]

This won't work because list only has elements with indices 0 and 1, not 4 and 5.

查看更多
登录 后发表回答