ChatGPT解决这个技术问题 Extra ChatGPT

CSV file written with Python has blank lines between each row

import csv

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

  for row in data:
        counter[row[10]] += 1


with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[10]] >= 504:
           writer.writerow(row)

This code reads thefile.csv, makes changes, and writes results to thefile_subset1.

However, when I open the resulting csv in Microsoft Excel, there is an extra blank line after each record!

Is there a way to make it not put an extra blank line?

Please confirm that this happens when you run that code on Windows
See the answer on this thread: stackoverflow.com/questions/3348460/…
Wouldn't setting lineterminator='\n' as default parameter for the initialization of csv.writer solve the problem? Want somebody do a Python 3.10 PR for this?
BTW, here are the official examples: docs.python.org/3/library/csv.html?highlight=csv#examples

M
Mark Tolonen

The csv.writer module directly controls line endings and writes \r\n into the file directly. In Python 3 the file must be opened in untranslated text mode with the parameters 'w', newline='' (empty string) or it will write \r\r\n on Windows, where the default text mode will translate each \n into \r\n.

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

In Python 2, use binary mode to open outfile with mode 'wb' instead of 'w' to prevent Windows newline translation. Python 2 also has problems with Unicode and requires other workarounds to write non-ASCII text. See the Python 2 link below and the UnicodeReader and UnicodeWriter examples at the end of the page if you have to deal with writing Unicode strings to CSVs on Python 2, or look into the 3rd party unicodecsv module:

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

Documentation Links

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

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


Anyway the @Mark Tolonen's answer did resolved many questions related to the extra line(s) added when saving a standard (no csv used) text file.
For compatibility between 2.6/2.7 and 3, you can use io.open with the newlines argument. If you're still writing in 2.x, that seems like a better choice anyway since it's forward compatible.
@jpmc26 Normally that's good advice, but the csv module doesn't work properly with io.open. There is a unicodecsv 3rd party module for Python 2.7 that works better.
Any idea why the newline='' trick doesn't work in python3 with StringIO or TemporaryFile?
My ultimate point is that if you use csv with pathlib.Path instead of open, the current answer results in \r\r\n newlines, even if you pass newline='' to the StringIO, and the solution is nonobvious. Now people can read these comments and find an answer and learn more about the nuance. Overriding lineterminator works, though it overrides the flavor settings, spites csvs encoding intentions, and muddies encoding across modules. Strangely, csv.writer() in Python 3 does not work with BytesIO, which I would expect it to, since it uses \r\n line endings by default.
D
David Maddox

Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.

Instead, you should keep it in text mode, but override the newline as empty. Like so:

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

J
John Machin

The simple answer is that csv files should always be opened in binary mode whether for input or output, as otherwise on Windows there are problems with the line ending. Specifically on output the csv module will write \r\n (the standard CSV row terminator) and then (in text mode) the runtime will replace the \n by \r\n (the Windows standard line terminator) giving a result of \r\r\n.

Fiddling with the lineterminator is NOT the solution.


What is this CSV "standard" of which you speak?
@Dan: I used "standard" as an adjective, not a noun, meaning "usual" or "commonplace". If you want an approximation to a (noun) standard, read tools.ietf.org/html/rfc4180
Point is (as you imply) that there is no standard. That RFE is Informational. While \r\n may be "standard" on Windows, I'm sure Unix applications typically don't see it that way.
@Dan: That is correct -- there is no standard. Scripts should specify the lineterminator [should have been named ROWterminator] that they want (if not the default) and still use binary mode in case the script is run on Windows otherwise the "lineterminator" may be stuffed up.
J
Jean-François Fabre

Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.

From Python Docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Original:

As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

I was about to post about this -- lineterminator='\n' worked for me in a simple test.
can i do this>?? with open('/pythonwork/thefile_subset11.csv', 'w'),lineterminator='\n' as outfile:
@I__ : You really should start perusing the Python docs. Derek gave you the link : docs.python.org/library/csv.html
The documentation for csv.writer and csv.reader has been updated since the original post back in 2010. It now recommends using newline='' when you open the file.
A
AustinDahl

A lot of the other answers have become out of date in the ten years since the original question. For Python3, the answer is right in the documentation:

If csvfile is a file object, it should be opened with newline=''

The footnote explains in more detail:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.


D
Debanjan Dey

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.


This is incorrect. with open('my_file.csv', 'a',newline='') as csvfile: works absolutely fine. The problem with your answer is that here you're writing ' ' instead of ''
May be so, in my system it worked like that
F
Febin Mathew

Use the method defined below to write data to the CSV file.

open('outputFile.csv', 'a',newline='')

Just add an additional newline='' parameter inside the open method :

def writePhoneSpecsToCSV():
    rowData=["field1", "field2"]
    with open('outputFile.csv', 'a',newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(rowData)

This will write CSV rows without creating additional rows!


thank you! the newline='' worked perfect for my application
S
SheRa
with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

The "lineterminator='\r'" permit to pass to next row, without empty row between two.


p
phantom-99w

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

One of the best posts here! Very helpful. Working. No more comments. ;-)
G
Golden Lion

I used writerow

def write_csv(writer, var1, var2, var3, var4):
    """
    write four variables into a csv file
    """
    writer.writerow([var1, var2, var3, var4])      
        
numbers=set([1,2,3,4,5,6,7,2,4,6,8,10,12,14,16])
rules = list(permutations(numbers, 4))
#print(rules)
selection=[]
with open("count.csv", 'w',newline='') as csvfile:
    writer = csv.writer(csvfile)

    for rule in rules:
        number1,number2,number3,number4=rule
        if ((number1+number2+number3+number4)%5==0):
            #print(rule)
            selection.append(rule)
            write_csv(writer,number1,number2,number3,number4)

a
anothernode

When using Python 3 the empty lines can be avoid by using the codecs module. As stated in the documentation, files are opened in binary mode so no change of the newline kwarg is necessary. I was running into the same issue recently and that worked for me:

with codecs.open( csv_file,  mode='w', encoding='utf-8') as out_csv:
     csv_out_file = csv.DictWriter(out_csv)