r/programmingrequests • • Jun 26 '19

Adding filename to each row in excel file

Howdy. I am using the code from here to combine multiple csv files. My knowledge of vba is mostly copy pasting and google-fu.

What I am requesting for is a piece of code that will add the file name to each row of the column after the last column of each csv file before it is combined so that I can identify which file the data has come from.

OR

A program from scratch which will copy/paste the name of the csv file to the last column of each row of the particular csv file and then combine them (copy paste them on top of each other (the csv filenames are years 2015, 206, 2017 and so on, so they will hopefully be pasted in order (but it is not necessary)).

Appreciate any help. Thank you.

2 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/POGtastic Jun 27 '19

Just to be clear - is it doing something like the following:

Foo,Bar,Baz,Filename
1,2,3,file1.txt

4,5,6,file1.txt

7,8,9,file2.txt

That makes me think that somehow, a newline is making its way into the filename string somewhere.


The last part is relatively straightforward:

import os

def remove_extension(filename):
    return os.path.splitext(filename)[0]

When adding the Filename to the dictionary, add the above function call.

1

u/jon_snow82 Jun 27 '19

There's a new row after the first one as well.

1

u/POGtastic Jun 27 '19

I figured it out - on Windows, the DictWriter needs the additional argument of lineterminator='\n'. Otherwise, it'll write '\r\n' at the end of every row.

So replace

out_writer = csv.DictWriter(out, fieldnames)

with

out_writer = csv.DictWriter(out, fieldnames, lineterminator='\n')