Skip to content Skip to sidebar Skip to footer

Add The Name Of The File To The Combined Csv File

I am new to Python. I have a set of CSV files, and I was able to combine them into one file using os.chdir('../Stok list') extension = 'csv' all_filenames = [i for i in glob.glob(

Solution 1:

This should work:

os.chdir("../Stok list")

extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

combined_csv = []
for f in all_filenames:
    df = pd.read_csv(f)
    df['filename'] = [f] * len(df.index)
    combined_csv.append(df)
combined_csv = pd.concat(combined_csv)
combined_csv.to_csv( "../combined_csv.csv", index=False, encoding='utf-8-sig')

It should add a column named filename to your final csv. Note that if your original file has incompatible columns or a column named filename the code will fail or behave in some strange unexpected way.

Post a Comment for "Add The Name Of The File To The Combined Csv File"