1

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,

2 Answers2

3

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

writer3.writerow([item, ''])
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

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)+',')
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52
  • That will iterate through each character. The 10th line will be `1,0,","`. And everything above it will be `X,","` where X is from 1 to 9. Not exactly what the OP wanted. As a note, `print()` and `writerow()` don't behave the same. – alvits Aug 01 '17 at 02:27
  • evenArray = ["hello",2,3,4] for item in evenArray: print(str(item)+',' ) output : hello, 2, 3, 4, – Hariom Singh Aug 01 '17 at 02:29
  • Only `print()` will do that. `writerow()` won't. Try it. – alvits Aug 01 '17 at 02:29
  • @alvits thanks you are right ..but char can be converted to string – Hariom Singh Aug 01 '17 at 02:30
  • Saying _so you can use_ **`writer2.writerow(str(item)+',')`** is reckless. – alvits Aug 01 '17 at 02:32
  • Again you are telling the OP to write `1,0,","` and `X,","` is plain wrong. Try to suggest something that actually works. – alvits Aug 01 '17 at 02:33