PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 30, 2022

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

 August 30, 2022     csv, dataframe, pandas, python     No comments   

Issue

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)

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)


Answered By - nogmos
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing