0

I need a help adding a simple solution to my problem. In writer for csv

with open(os.path.join(self.current_dir, csv_filename), 'w') as f:
                writer = csv.writer(f)
                writer.writerows(rows)

I CAN'T add newline='' because it causes some bugs in logic, and totally mess up my results. Soo i came up to solution, but unfortunately i dont know Python very well. Is there any way to write a loop that will remove ALL empty rows from csv file after it has been written ? It is for Python 3.4

EDIT:

As people pointed out, newline and using binary writing is the way to go for this problem in windows, but my real question is, can a loop that removes empty rows from csv file be implemented in same script or does it need a seperate script that does the removing ? Either way will work for me.

  • Sounds like you might be writing csv files in windows. check this out http://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return – John Mar 28 '16 at 02:34
  • Yes, writing in windows. And i try adding ' writer = csv.writer(f, lineterminator='\n') ' but it still produce same bugs, i just need a end loop that will open said csv file, remove empty rows and write it back. – Ilija Sinadinovic Mar 28 '16 at 02:43
  • Did you open the file in binary mode as well? – John Mar 28 '16 at 02:44
  • No, because data is not in binary format, it uses PyQT for some GUI, and somewhere in that syntax something is causing bugs if i try to remove empty rows with newline='' and lineterminator – Ilija Sinadinovic Mar 28 '16 at 02:47
  • thats why i need writer to stay as it is and just add a loop that will remove all empty rows from created csv file – Ilija Sinadinovic Mar 28 '16 at 02:48
  • Have you tried opening the file in 'wb' mode? I just ran a sample program on my computer first with the file open in 'w' mode and I got the extra lines then in 'wb' mode which got rid of the extra lines. – John Mar 28 '16 at 02:56
  • Nop, i try that already, it returns error TypeError: 'str' does not support the buffer interface. Thats why i need this loop when the csv is already created. – Ilija Sinadinovic Mar 28 '16 at 03:01
  • The "official" answer (described in [the `csv` module's documentation](https://docs.python.org/3/library/csv.html#csv.writer)) is to use `newline=""` when opening the file. If you're having some issue with that, please describe the error and maybe we can help you. It's not very useful to rule out the correct answer! – Blckknght Mar 28 '16 at 04:48
  • that is the thing, adding newline works like a charm, no more empty rows but it messes my last colume, which contains my input from script in adding "yes" or "no" comments in such way that for example for 50 results i press 20 yes, then 20 no, then 10 yes, but in csv is more like 19 Y/2 N/ empty comment / 19 N / 9 Y – Ilija Sinadinovic Mar 28 '16 at 10:07

0 Answers0