4

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()
M. of CA
  • 1,496
  • 2
  • 22
  • 32
  • You do realise there is no actual empty line added? Open the file for reading and do `for line in myFile:print(repr(line))`, you won't see any empty line. – Padraic Cunningham Mar 30 '15 at 00:11
  • 1
    Padraic, you're probably on an Unix system. In Unix there's no line added, in Windows there is. Seems inconsistent. – misantroop Nov 10 '18 at 18:42

4 Answers4

2

I couldn't find an answer that will work in python 3 and also for my case so here is my solution:

def remove_last_line_from_csv(filename):
    with open(filename) as myFile:
        lines = myFile.readlines()
        last_line = lines[len(lines)-1]
        lines[len(lines)-1] = last_line.rstrip()
    with open(filename, 'w') as myFile:    
        myFile.writelines(lines)
arispen
  • 2,832
  • 1
  • 15
  • 13
2

I appreciate that this is an old request but I stumbled across it whilst looking for the same solution. I ended up reading the answer in the csv documentation itself and found that csv.writer has a lineterminator formatting parameter which defaults to \r\n, giving the new rows we both didn't want.

As a solution I added the formatting parameter newline='' to the code and it works well (in situ below).

    with open(fname, 'wb') as myFile:
        # Start the CSV Writer
        wr = csv.writer(myFile, delimiter=',', dialect='excel', lineterminator='')
        wr.writerows(rows)
Gary
  • 67
  • 1
  • 9
Vonron
  • 21
  • 3
2

Thanks to wfgeo one of the solution works like this. Although it requires os library it makes life a little bit easier:

import csv
import os

with open(fileName, 'w', newline='') as f:
  writer = csv.writer(f, delimiter=';', dialect='excel')
  
  for row in rows:
    row = rows[0].values()
    writer.writerow(row)

  f.seek(0, os.SEEK_END)
  f.seek(f.tell()-2, os.SEEK_SET)
  f.truncate()
Roman
  • 19,236
  • 15
  • 93
  • 97
1

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.

Community
  • 1
  • 1
Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
  • 1
    csv.writer has no write method, if the rows contained ints etc.. join would fail. The output will also be the same for all the examples if you just used the original code. – Padraic Cunningham Mar 30 '15 at 00:07