【问题标题】:Applying same code to multiple files within multiple folders将相同的代码应用于多个文件夹中的多个文件
【发布时间】:2016-10-15 13:43:48
【问题描述】:

我有一个包含许多子目录(更多文件夹)的文件夹,每个子目录中都有 csv 文件。我想将相同的代码应用于子目录中的所有 csv 文件。如果我只为一个文件夹这样做,我会这样做:

list1=[]  
pth=r'G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_crp\05f08_46e'   
for f in os.listdir(pth):
    out=r'G:\Stefano\Ecoregion_assessment\final_files'
    df=pd.read_csv(os.path.join(pth,f))
    columns=['Percent', 'Land_Use', 'LC_Source']
    df=df[columns]
    df['Land_Use2']=df.Land_Use
    df.rename(columns={'Percent': 'Percent_' +df.iloc[1,2], 'Land_Use': 'Land_Use_' +df.iloc[1,2]} , inplace=True)
    df.drop(['LC_Source'], inplace=True, axis=1)
    list1.append(df)
    df_final = reduce(lambda left,right: pd.merge(left,right,on=['Land_Use2'], how='outer'), list1)
df_final.to_csv(os.path.join(out,'05f08_46e.csv'))

在这种情况下,G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_crp 是导航到所有子目录的根,05f08_46e 是子目录之一。我想使用一个函数将相同的代码应用于根目录中的所有文件夹,然后将df_final 文件发送到out 以及正在循环的特定子目录的名称。我在G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_crp 中有 20 个文件夹,因此我希望最后有 20 个输出文件到G:\Stefano\Ecoregion_assessment\final_files。我只是想将我编写的代码应用到所有 20 个文件夹,而无需手动更改文件夹路径。

解决此问题的另一种可能方法是使用os.walk,但我一直在尝试使用它,但还没有成功。

【问题讨论】:

    标签: python csv pandas


    【解决方案1】:

    只需添加一个额外的循环。我已经尝试重写您的代码,即使缺少某些部分并且我无法对其进行测试,但我对此非常有信心:

    pth=r'G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_crp'  # upper dir  
    out=r'G:\Stefano\Ecoregion_assessment\final_files' # out of the loop
    
    for d in os.listdir(pth):
        # 05f08_46e will be one of the "d" values
        for f in os.listdir(os.path.join(pth,d)):
          df=pd.read_csv(os.path.join(pth,f))
          columns=['Percent', 'Land_Use', 'LC_Source']
          df=df[columns]
          df['Land_Use2']=df.Land_Use
          df.rename(columns={'Percent': 'Percent_' +df.iloc[1,2], 'Land_Use': 'Land_Use_' +df.iloc[1,2]} , inplace=True)
          df.drop(['LC_Source'], inplace=True, axis=1)
          list1.append(df)
          df_final = reduce(lambda left,right: pd.merge(left,right,on=['Land_Use2'], how='outer'), list1)
        df_final.to_csv(os.path.join(out,d+'.csv'))
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多