Skip to content
Advertisement

Python CSV Writer leave a empty line at the end of the file

the following code leave a empty white line at the end of the txt file. how can i not have the writerows not terminate the last line?

        with open(fname, 'wb') as myFile:
        # Start the CSV Writer
        wr = csv.writer(myFile, delimiter=',', dialect='excel')
        wr.writerows(rows)

        # Close the file.
        myFile.close()

Advertisement

Answer

Firstly, since you are using with open as myFile you don’t need myFile.close(), that is done automatically when you remove the indent.

Secondly, if you are willing to add another part to your program, you could simply write something that removes the last line. An example of this is made by Strawberry (altered slightly):

with open(fname) as myFile:
    lines = myFile.readlines()
with open(fname, "w") as myFile:
    myFile.writelines([item for item in lines[:-1]])

Note how the ‘w’ parameter will clear the file, so we need to open the file twice, once to read and once to write.

I also believe, you are able to use myFile.write, which doesn’t add newlines. An example of using this would be:

with open(fname, 'wb') as myFile:
    wr = csv.writer(myFile, delimiter=',', dialect='excel')
    lines = []
    for items in rows:
        lines.append(','.join(items))
    wr.write('n'.join(lines))

This however will only work if you have a multi-dimensional array, and should probably be avoided.

Advertisement