CSV file written with Python has blank lines between each row

后端 未结 9 1560
青春惊慌失措
青春惊慌失措 2020-11-21 10:04
import csv

with open(\'thefile.csv\', \'rb\') as f:
  data = list(csv.reader(f))
  import collections
  counter = collections.defaultdict(int)

  for row in data:
          


        
9条回答
  •  伪装坚强ぢ
    2020-11-21 10:49

    I'm writing this answer w.r.t. to python 3, as I've initially got the same problem.

    I was supposed to get data from arduino using PySerial, and write them in a .csv file. Each reading in my case ended with '\r\n', so newline was always separating each line.

    In my case, newline='' option didn't work. Because it showed some error like :

    with open('op.csv', 'a',newline=' ') as csv_file:
    
    ValueError: illegal newline value: ''
    

    So it seemed that they don't accept omission of newline here.

    Seeing one of the answers here only, I mentioned line terminator in the writer object, like,

    writer = csv.writer(csv_file, delimiter=' ',lineterminator='\r')

    and that worked for me for skipping the extra newlines.

提交回复
热议问题