CSV file written with Python has blank lines between each row

后端 未结 9 1565
青春惊慌失措
青春惊慌失措 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:45

    Borrowing from this answer, it seems like the cleanest solution is to use io.TextIOWrapper. I managed to solve this problem for myself as follows:

    from io import TextIOWrapper
    
    ...
    
    with open(filename, 'wb') as csvfile, TextIOWrapper(csvfile, encoding='utf-8', newline='') as wrapper:
        csvwriter = csv.writer(wrapper)
        for data_row in data:
            csvwriter.writerow(data_row)
    

    The above answer is not compatible with Python 2. To have compatibility, I suppose one would simply need to wrap all the writing logic in an if block:

    if sys.version_info < (3,):
        # Python 2 way of handling CSVs
    else:
        # The above logic
    

提交回复
热议问题