如何为我目录中的每个文件运行此python函数?

问题描述

我有一个应该清除列表中包含的csv文件功能

fileListLocalDaily = (glob.glob("/path/to/my/directory/*.csv")
for y in fileListLocalDaily:
    data = y
    def prepare_file(y):
        data = y
        lines = pd.read_csv(data,sep=",",quoting=csv.QUOTE_NONE)
        new_lines = lines.replace('something','',regex=True)
        f = StringIO(data)
        # extract date
        date = next(f)
        date = date.split('_')[1]
        date = os.path.splitext(date)[0]
        new_lines.insert(2,'date',date)
        new_lines.drop(new_lines.columns[0:2],axis=1,inplace=True)
        new_lines.drop(new_lines.columns[6],inplace=True)
        new_lines=new_lines.sort_values(by=['Something'],ascending=False) 
        new_lines.to_csv('/path/to/my/output/'+date+'.csv',index = False)
        complete = prepare_file(data)
runFunction = prepare_file(y)

上面的函数似乎只保存了一个文件,并不断循环覆盖它。有人可以帮助我了解如何在目录中一个一个地对所有csv文件运行此功能吗?谢谢

解决方法

根据您提供的代码,您的循环实际上没有执行任何操作。您要一遍又一遍地定义该函数,但是您不会在循环中调用它,因为最后一行的缩进不在循环中。您的函数最后也调用了自己,因此它进入了无限循环。您应该定义一次函数,然后在循环内部调用它:

def prepare_file(data):
    lines = pd.read_csv(data,sep=",",quoting=csv.QUOTE_NONE)
    new_lines = lines.replace('something','',regex=True)
    f = StringIO(data)
    # extract date
    date = next(f)
    date = date.split('_')[1]
    date = os.path.splitext(date)[0]
    new_lines.insert(2,'date',date)
    new_lines.drop(new_lines.columns[0:2],axis=1,inplace=True)
    new_lines.drop(new_lines.columns[6],inplace=True)
    new_lines=new_lines.sort_values(by=['Something'],ascending=False) 
    new_lines.to_csv('/path/to/my/output/'+date+'.csv',index = False)

fileListLocalDaily = (glob.glob("/path/to/my/directory/*.csv")
for data in fileListLocalDaily:
    prepare_file(data)

prepare_file不返回任何内容,因此赋值运算符只是在此处赋值None,因此我删除了赋值。在循环和函数中,我还直接将y重命名为data

,

我喜欢使用os.walk递归获取所有文件

import os
top = '/path/to/my/directory'
for root,dirs,files in os.walk(top):
for name in files:
    if os.path.splitext(name) == ".csv":
        # do stuff with name here
        # use os.path.join(root,name) for the full file path