CSV file written with Python has blank lines between each row

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

    In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

    In Python 3 the required syntax changed (see documentation links below), so open outfile with the additional parameter newline='' (empty string) instead.

    Examples:

    # 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)
    

    Documentation Links

    • https://docs.python.org/2/library/csv.html#csv.writer
    • https://docs.python.org/3/library/csv.html#csv.writer

提交回复
热议问题