Joe Ackerson
Joe Ackerson

Reputation: 27

Python CSV output formatting

I need to output the CSV file text in three files for odds, evens and all numbers. However, Right now it only has them being printed on a single line in an array format when you run the program. I need all the numbers to be on their own individual lines separated by commas.

For example:

1,
2,
3,
4,
5,

I can use loops on all the writerows as seen in the code below however this option crates values separated like

1,

2,

3,

4,

5,

I would like to avoid this and just use .join or the newline, or even something else in order to get the correct output, but I could not get either to work and don't have a ton of experience in formatting csv files.

import csv
from tkinter import *

myGui = Tk()
myGui.title("Label Creator    v: 0.01")
myGui.geometry("290x70")

allArray = []
oddArray = []
evenArray = []

Label(myGui, text="Starting value: ").grid(row=0)
Label(myGui, text="Ending value: ").grid(row=1)

a = IntVar()
b = IntVar()

e1 = Entry(myGui, textvariable=a)
e1.grid(row=0, column=1)
e2 = Entry(myGui, textvariable=b)
e2.grid(row=1, column=1)

def main():
    oute1 = a.get()
    oute2 = b.get()
    for i in range(oute1, oute2 + 1):
        x = i
        allArray.append(x)
        # Odds
        if(x % 2 == 1):
            oddArray.append(x)
        # Evens
        elif(x % 2 == 0):
            evenArray.append(x)

    with open("all_labels", "w") as outputFile1:
        writer1 = csv.writer(outputFile1)
        for k in allArray:
            writer1.writerow([k])

    with open("odd_labels", "w") as outputFile1:
        writer2 = csv.writer(outputFile1)
        for k in oddArray:
            writer2.writerow([k])

    with open("even_labels", "w") as outputFile2:
        writer3 = csv.writer(outputFile2)
        for k in evenArray:
            writer3.writerow([k])


Button(myGui, text="Start", command=main).grid(row=3)

myGui.mainloop()

Upvotes: 0

Views: 923

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191973

I need all the numbers to be on their own individual lines separated by commas.

First, you don't need the csv module for this

Second, I would define a function so that you're not repeating yourself.

def write_numbers(filename, nums):
    with open(filename, "w") as f:
        for x in nums:
            f.write("{},\n".format(x))

Then call that for each of your needed outputs

write_numbers("all_labels.txt", allArray) 
write_numbers("odd_labels.txt", oddArray)  
write_numbers("even_labels.txt", evenArray) 

Upvotes: 0

caxcaxcoatl
caxcaxcoatl

Reputation: 8980

If all you want is to force the csv module to print the commas, you can give it a null second column:

    writer1.writerow ([k, None])

Now, if that is really all that you want, I don't think you should be using the csv module to begin with. It would be easier to just write to the file directly:

outputFile1.write ("%d,\n" % k)

Upvotes: 1

Related Questions