L.Mack
L.Mack

Reputation: 9

csv writer adding unwanted commas

This section of my code writes a .CSV file using the output of a tkinter optionmenu, which works fine, but my written file includes commas between each character, I want it between the variable, string and date.time reference.

This is how it appears:

S,h,u,t,t,l,e, ,1, ,R,e,m,o,v,e,d, ,@, ,2,0,1,8,-,0,7,-,0,8, ,0,9,:,4,6,:,3,8

S,h,u,t,t,l,e, ,2, ,R,e,m,o,v,e,d, ,@, ,2,0,1,8,-,0,7,-,0,8, ,0,9,:,4,6,:,3,8

And I want this:

Shuttle 1, Removed @ 2018-07-08 09:46:38

Shuttle 2, Removed @ 2018-07-08 09:46:38

def shuttle_removed():    
    removed = open("Todays-Adapto.csv", "a", newline="")
    removed_write = csv.writer(removed)
    removed_write.writerow(var_1_default.get()+" Removed @ "+now_date)
    removed.close()

I'm using Python 3.7, if any other info is needed just ask. Thanks.

Upvotes: 1

Views: 1321

Answers (1)

abarnert
abarnert

Reputation: 366073

The problem is that you're passing one big string as the row. But writerow wants a sequence of strings. Because a string is a sequence of all of its characters, writerow turns each character into its own column.

If you want to write single-column rows (but then why are you even using a CSV file in the first place instead of just a plain text file?), you need to pass a list or tuple of one string, not just the string:

removed_write.writerow([var_1_default.get()+" Removed @ "+now_date])

If you want two columns, you need to pass a list or tuple of two strings, not add all the strings together:

removed_write.writerow([var_1_default.get(), " Removed @ "+now_date])

If you want three columns… you get the idea:

removed_write.writerow([var_1_default.get(), " Removed @ ", now_date])

Upvotes: 1

Related Questions