Home > Software engineering >  How to add filename as column to every file in a directory python
How to add filename as column to every file in a directory python

Time:06-09

Hi there stack overflow community,

I have several csv-files in a folder and I need to append a column containing the first 8 chars of each filename in a aditional column of the csv. After this step i want to save the datafram including the new colum to the same file.

I get the right output, but it doesn't save the changes in the csv file :/

Maybe someone has some inspiration for me. Thanks a lot!

from tkinter.messagebox import YES
import pandas as pd
import glob, os

import fnmatch
import os



files = glob.glob(r'path\*.csv')

for fp in files:
    df = pd.concat([pd.read_csv(fp).assign(date=os.path.basename(fp).split('.')[0][:8])])
#for i in df('date'):
#Decoder problem


print(df)

CodePudding user response:

use: df.to_csv

like this:

for fp in files:
    df = pd.concat([pd.read_csv(fp).assign(date=os.path.basename(fp).split('.')[0][:8])])  
    df.to_csv(fp, index=False)  # index=False if you don't want to save the index as a new column in the csv

btw, I think this may also work and is more readable:

for fp in files:
    df = pd.read(fp)
    df[date] = os.path.basename(fp).split('.')[0][:8]
    df.to_csv(fp, index=False)
  • Related