0

I would like to eliminate blank gap row after row! Please refer to the pic for better overview. What is wrong with the code? notepad format seems fine while when viewed from excel, space just occur for every entries including the first time after the header input

user2947950
  • 129
  • 1
  • 2
  • 8

1 Answers1

1

Depending on the python version you are using:

# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Credits to: https://stackoverflow.com/a/3348664/5415084

So, in summary: python 3 requires an additional parameter newline='' while using the w parameter and python 2 requires the wb parameter while opening the file.

Community
  • 1
  • 1
Leustad
  • 375
  • 1
  • 5
  • 20
  • python 2.7 here – user2947950 Sep 26 '16 at 13:31
  • Did you try what's been described above? Is it working for you? – Leustad Sep 26 '16 at 13:33
  • i merely added "b" in wb `with open("sample_data.csv") as f, open("out.csv", "w") as out:` however error returned Traceback (most recent call last): File "C:\Users\xxxx\Desktop\Function 6 - still in progress.py", line 7, in next(reader) StopIteration – user2947950 Sep 26 '16 at 13:37
  • Change 2 - `with open("sample_data.csv", "wb" ) as f, open("out.csv", "wb") as out:` Traceback (most recent call last): File "C:\Users\Acer\Desktop\Function 6 - still in progress.py", line 7, in next(reader) IOError: File not open for reading – user2947950 Sep 26 '16 at 13:41
  • Is the previous run still running? – Leustad Sep 26 '16 at 13:43
  • 1
    `"sample_data.csv"` needs to be opened `"rb"` not `"wb"`. – Steven Rumbalski Sep 26 '16 at 13:44
  • previous refering to the first change? @Steven Rumbalski Traceback (most recent call last): File "C:\Users\xxxx\Desktop\Function 6 - still in progress.py", line 7, in next(reader) StopIteration – user2947950 Sep 26 '16 at 13:44
  • use `rb` parameter on the file you will read from and use `wb` param on the file you will write to. Just like @StevenRumbalski said. – Leustad Sep 26 '16 at 13:48
  • 1
    @KaelTee: Your `"sample_data.csv"` is blank because on a previous run of your program it was opened for writing (`with open("sample_data.csv", "wb") as f`). So when you call `next(reader)` there is no next row because there are no rows in the file. Opening a file for writing overwrites the existing file. – Steven Rumbalski Sep 26 '16 at 13:48
  • @StevenRumbalski IT WORKS NOW! As you said, my sample_data.csv is blank. Thank ou! – user2947950 Sep 26 '16 at 13:53