【问题标题】:Loop through sub -directories, read files starting with given name and append遍历子目录,读取以给定名称开头的文件并追加
【发布时间】:2019-08-27 15:45:17
【问题描述】:

我有一个包含 CSV 文件的子目录的文件夹。每个子目录都有名为 modified.csv added_field.csv 和 denied.csv 的 CSV 文件。如何遍历每个子目录读取每个子目录中以修改、添加字段和停用名称开头的所有文件,然后递归地将它们附加在一起?

在这种情况下,我尝试了 os walk,但我不知道如何使用 os walk 按名称读取每个目录中的所有文件,追加并移动到下一个目录并执行附加到上一个表的相同过程。这是我的愚蠢代码

from os import walk
f = []
path ="working dir"
for (dirpath, dirnames, filenames) in walk(path):
     file1 = [filenames for filenames in os.listdir(path) if 
             filenames.startswith("modified")]
    file2 = [filenames for filenames in os.listdir(path) if 
            filenames.startswith("Added_field")]
    file3 = [filenames for filenames in os.listdir(path) if 
            filenames.startswith("Retired")]
    df1 = pd.read_csv(file1)
    df2 = pd.read_csv(file2)
    df3 = pd.read_csv(file3)
    Finalcombined_df = df1.append([df2,df3], sort=False)

我的意图是通过选择它们的起始名称来遍历每个子目录读取文件,因为那里还有其他文件,然后将它们附加在一起,并有一个最终的大表,它结合了每个子目录中的所有表

【问题讨论】:

    标签: python python-3.x dataframe


    【解决方案1】:
    
    from pathlib import Path
    
    p = Path.cwd()  # if you're in the current working dir
    p = Path('to level dir')  # insert a top level path of choice
    
    
    f_names = ['modified', 'Added_field', 'Retired']
    
    f = [y for x in f_names for y in p.glob(f'**/{x}*.csv') ]  # ** gets all sub-dirs
    
    df =  pd.concat([pd.read_csv(x) for x in f])
    

    【讨论】:

    • 为什么有些列的扩展名为 .1。认为它们应该与可用列匹配
    • @LivingstoneM 您的一个或多个文件中的 csv 文件中的列标题不唯一。
    【解决方案2】:

    您可以使用Path.rglob从所有子目录中获取所有文件

    from pathlib import Path
    
    path = '.'
    
    prefixes = ['modified', 'Added_field', 'Retired']
    
    found = []
    
    
    for file in Path(path).rglob('*.csv'):
        for p in prefixes:
            if file.name.startswith(p):
                found.append(file)
                break
    
    print(found)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      相关资源
      最近更新 更多