Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add filename as column to every file in a directory python

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 :/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading