Home > Enterprise >  How to add the folder filenames in a pandas column, where each name is the one where one csv concate
How to add the folder filenames in a pandas column, where each name is the one where one csv concate

Time:03-09

I am reading one csv file in several folder, everytime this is the same csv name.

I have this function:

def get_all_projects(path,var):
    folder=[]
    for i in os.listdir(path):
        folder.append(i)
    df=[]
    for x in range(len(folder)):
        try:
            df.append(pd.read_csv(path '\\' folder[x] '\\' var '.csv',sep=';',header=0))
        except:
            pass
    table = pd.concat(df)
    table = table.reset_index(drop=True)
    return(table)

The result of this function is a dataframe with all csvs concatenated.

I would like to add a column to this csv, the folder filename of each csv file.

How can I do this in the function ?

CodePudding user response:

You can do something along the lines:

Update the try block with below:

try:
    file_path = path '\\' folder[x] '\\' var '.csv'
    tmp = pd.read_csv(file_path, sep=';',header=0)
    tmp['folder_filename'] = file_path # tweak this for exact value
    df.append(tmp)
  • Related