Joe Ackerson
Joe Ackerson

Reputation: 27

Can't get commas to seperate my CSV values

I got the file to print in a vertical column, however, the values still need to be separated using commas and here is what the output looks like right now.

1
2
3
4
5
6
7
8
9
10

Here is the code that outputs the text to the CSV files.

with open("all_labels", "w") as outputFile:
    writer1 = csv.writer(outputFile, lineterminator='\n')
    for item in allArray:
        writer1.writerow([item])


with open("odd_labels", "w") as outputFile1:
    writer2 = csv.writer(outputFile1, lineterminator='\n')
    for item in oddArray:
        writer2.writerow([item])

with open("even_labels", "w") as outputFile2:
    writer3 = csv.writer(outputFile2, lineterminator='\n')
    for item in evenArray:
        writer3.writerow([item])

and I just need help to add in the commas back to the file if anybody has any suggestions so that the final output in the file will read.

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,

Upvotes: 1

Views: 65

Answers (2)

Barmar
Barmar

Reputation: 780808

If you want an extra separator, you can write a list with an extra, empty element in it:

writer3.writerow([item, ''])

Upvotes: 3

Hariom Singh
Hariom Singh

Reputation: 3632

Try something like below

evenArray = [1,2,3,4]

for item in evenArray:
        print(str(item)+',' )

Output

1,
2,
3,
4,

so you can use

writer2.writerow(str(item)+',')

Upvotes: 2

Related Questions