使用Glob写入多个CSV

时间:2018-11-30 06:17:48

标签: python pandas csv glob

我正在处理许多csv文件,需要添加列。我尝试了glob,例如:

import glob

filenames = sorted(glob.glob('./DATA1/*2018*.csv'))
filenames = filenames[0:10]

import numpy as np
import pandas as pd

for f in filenames:
    df = pd.read_csv(f, header=None, index_col=None)
    df.columns = ['Date','Signal','Data','Code']
 #this is what I should add to all csv files   
    df["ID"] = df["Data"].str.slice(0,2) 

,在将列添加到每个csv文件后,我需要一种方法将文件以其他名称(例如“ file01edited.csv”)保存回csv(未连接)。

1 个答案:

答案 0 :(得分:1)

to_csvf-string一起用于更改文件名:

for f in filenames:
    df = pd.read_csv(f, names=['Date','Signal','Data','Code'], index_col=None)
 #this is what I should add to all csv files   
    df["ID"] = df["Data"].str.slice(0,2) 
    #python 3.6+
    df.to_csv(f'{f[:-4]}edited.csv', index=False)
    #python bellow 3.6
    #df.to_csv('{}edited.csv'.format(f[:-4]), index=False)