1

I have a piece of python code which is supposed to open (or create) a CSV file and append a new row to the end of it. However, there is an extra blank line added between each entry. Is there a way to avoid this?

I have around 500 instances of the script which all access the same file, though (in theory) they should access the file at different times.

def writeBest(fileName, savePath, data):

    # Create a filename
    name = "BEST_" + fileName + ".csv"

    # Create the complete filename including the absolute path 
    completePath = os.path.join(savePath, fileName)

    # Check if directory exists
    if not os.path.exists(completePath):
        os.makedirs(completePath)

    completeName = os.path.join(completePath, name)

    # Write the data to a file
    theFile = open(completeName, 'wb')
    writer = csv.writer(theFile, quoting=csv.QUOTE_ALL)
    writer.writerow(data)

    # Close the file
    theFile.close()
Chris Headleand
  • 6,003
  • 16
  • 51
  • 69
  • 1
    What is data? which type? – Tom Ron Apr 23 '14 at 14:42
  • 2
    If you want to add to the csv file I'd imagine you want to open it with the `ab` mode, not `wb`. – Holloway Apr 23 '14 at 14:45
  • it needs to create the file if it doesnt exist – Chris Headleand Apr 23 '14 at 14:47
  • 1
    @ChrisHeadleand The `'a'` mode will create the file if it doesn't exist. (Test it yourself.) Anyway, can you show us a same of your `data` argument? – 2rs2ts Apr 23 '14 at 14:50
  • @ChrisHeadleand the w will overwrite a file if it already exists rather than add to it. – Holloway Apr 23 '14 at 14:52
  • Can you tell us what `writer.dialect.lineterminator` is? It should be `'\r\n'` since you didn't specify a dialect (it'll default to `'excel'` in that case) but maybe it's not. – 2rs2ts Apr 23 '14 at 14:56
  • See the answer on this thread: https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row/#53577233 – Febin Mathew Dec 02 '18 at 04:00

2 Answers2

3

Problem answered through comments. The issue was using the wb mode not ab mode.

Chris Headleand
  • 6,003
  • 16
  • 51
  • 69
  • 1
    You might want to explain a bit more: it's not clear how this could solve your problem. Opening the file with mode `"wb"` would clobber what was there before, not append but introduce extra blank lines. – DSM Apr 23 '14 at 15:32
0

the 'b' option dose the trick for me, check the API doc: https://docs.python.org/2/library/functions.html?highlight=open#open