dwb
dwb

Reputation: 483

Removing blank lines while creating file

I have a script that creates files for each line of a CSV file. However, somehow a blank line is being added to the end of the newly created file.

Code:

 with open(fullCSV, 'r') as f:
            reader = csv.reader(f)
            csvList = list(reader)

        for item in csvList:
            if not os.path.exists(tempLoc + item[0]):
                os.mkdir(tempLoc + item[0])
            with open(tempLoc + item[0] + r"\prm.263", "w+") as f:
                csv.writer(f).writerow(item[1:])
            f.close

Is there some way I can strip the blank line on creation?

Thanks in advance

Edit:

Here is the sample of 1 of the output files that is being created enter image description here

Here is the CSV file its reading enter image description here

Upvotes: 2

Views: 683

Answers (2)

Guillaume
Guillaume

Reputation: 6009

csv.writer by default uses the excel dialect, which has a '\r\n' as lineterminator.

If you really don't want any line terminator, you can override that with the lineterminator parameter to csv.writer():

csv.writer(f, lineterminator='').writerow(item[1:])

Since you only write 1 single line in each file, you will not have an issue with all original lines ending up concatenated in 1 single line in your output.

Your sample code rewritten:

with open(fullCSV, 'r') as finput:
    for item in csv.reader(finput):
        if not os.path.exists(tempLoc + item[0]):
            os.mkdir(tempLoc + item[0])
        with open(tempLoc + item[0] + r"\prm.263", "w+") as foutput:
            csv.writer(foutput, lineterminator='').writerow(item[1:])

Upvotes: 2

adrtam
adrtam

Reputation: 7211

The issue is the csv module. You can see that there is no way to get rid of the end of line character from the output of writerow(). After all, the csv module assume you can repeatedly write rows:

 writer.writerow(row1)
 writer.writerow(row2)
 ...

so emitting a newline on every row output is necessary to make it work. But your question is to remove the newline at end of file. So you can consider adding an extra step in between: (using Python 3 io module)

with open(tempLoc + item[0] + r"\prm.263", "w+") as f:
    g = io.StringIO()
    csv.writer(g).writerow(item[1:])
    f.write(g.getvalue().rstrip())

Above, we make a StringIO as file-like object for csv.writer() and ask the writer to write to the buffer instead of the file. After you finish writing all the rows, we read the buffer by g.getvalue() and then strip out the whitespaces (i.e., the newline) at the end, and write to the file.

If you're interested, this is what the csv module will give you for each row:

>>> import io
>>> f = io.StringIO()
>>> import csv
>>> csv.writer(f).writerow([1,2,3,4])
9
>>> f.getvalue()
'1,2,3,4\r\n'

Upvotes: 3

Related Questions