0

Normally when I open a CSV file in Python, I need to use:

with open(filename, newline='', mode='w') as f:

And if I don't have that newline='' in there, it creates an empty line between each line in my CSV. However, I am using Tkinter to save the file, so I have:

new_filename = asksaveasfile(mode='w', defaultextension='.csv')

Since "new_filename" is already open, I can't do the "open" command to indicate the newline='' in there. If I try opening it again, I get an error. So how do I get rid of the extra spaces in this case?

Thanks for your help and patience.

Emac
  • 1,098
  • 3
  • 18
  • 37
  • It's bizarre that you have to use the `newline` argument. Are you sure that whatever viewer you're using isn't misinterpreting, for example `\r\n` as two newlines, or that your data doesn't have newlines already in it? I've never had that. – jedwards Jun 12 '18 at 18:36

1 Answers1

2

you have some other problem regarding the new line parameter - I don't have to use it at all here. But for your tkinter problem, you can use asksaveasfilename instead. That returns the selected file name, then you can open it in any way you want.

nosklo
  • 217,122
  • 57
  • 293
  • 297
  • The newline parameter seems fairly common, I've encountered many other Stack Overflow posts about it. Here's just a couple examples: https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return https://stackoverflow.com/questions/30929363/csv-writerows-puts-newline-after-each-row I'm not sure I follow what you mean by use "asksaveasfile" instead? I already am using it, as provided in the code I showed above. What would I use it instead of? – Emac Jun 12 '18 at 18:43
  • 1
    `asksaveasfilename` @Emac – nosklo Jun 12 '18 at 18:44
  • Thanks, I missed that key word "name" ... and that fixed it! Much thanks. – Emac Jun 12 '18 at 18:50