遍历子目录中的文件并加载它们

2024-04-25 20:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要解决以下情况:我的父目录有~25个子文件夹。每个子文件夹都包含一个以“RRS.csv”结尾的文件。此外,某些子文件夹包含以“ROH.csv”结尾的文件。从每个子文件夹中,我需要导入“ROH.csv”文件(如果存在),如果没有,则导入“RRS.csv”文件。我尝试通过使用os.path.exists操作符遍历所有子文件夹和子文件夹中的所有文件来检查“ROH.csv”文件是否存在。另一个想法是首先列出每个子文件夹中的所有文件,然后确定一个元素是否包含以“ROH.csv”结尾的元素,然后加载它

for filename in sorted(os.listdir(parent_dir)):
    for subdir, dirs, files in os.walk(parent_dir):
        if not os.path.exists(filename.endswith('ROH.csv')):
            data = np.genfromtxt(filename.endswith('RRS.csv'), delimiter=',', skip_header=1)
            # some calculations
        else:
            data = np.genfromtxt(filename.endswith('ROH.csv'), delimiter=',', skip_header=1)
            # more funny calculations

此代码有多个问题:(i)它必须检查子文件夹中的一个文件是否以“ROH.csv”结尾,而不是每个文件是否以它结尾;(ii)我还没有找到一种方法来指定加载哪个文件;endswith不工作(bool);(iii)它包含双for循环

希望有人有办法解决这个问题


2条回答

我不确定我是否理解您提到的问题,但这里有一个片段,可以为您提供要处理的文件列表。您可以用更聪明或可读的方式更改筛选,但我已经用一个级别的嵌套文件夹对此进行了测试,它完成了这项工作。你可以从这里开始写一些更清晰或更适合你需要的东西

#parent_dir=os.getcwd()+"\\temp" 
files_to_read=[]
walk = [(subdir, dirs, files) for (subdir, dirs, files) in os.walk(parent_dir) if not (subdir==parent_dir)]  #Skip the root directory
for (subdir, dirs, files) in walk:
    file_to_read = list(filter(lambda x: "ROH.csv" in x or "RRS.csv" in x, files)) #Explicitly filter for one of the two strings
    if len(file_to_read)>1:
        file_to_read = list(filter(lambda x: "ROH.csv" in x, files))[0]      #explictly pick the ROH file if there are both files
    elif len(file_to_read)>0:
        file_to_read = file_to_read[0]                           #Otherwise pick the only file in the list i.e. RRS
    file_to_read=subdir+os.path.sep+file_to_read
    files_to_read.append(file_to_read)

这是假设您需要对ROH文件和RRS文件执行不同的操作:

def get_files_with_suffix(root, files, suffix):
    return [os.path.join(root, filename) for filename in files if filename.endswith(suffix)]

for root, dirs, files in os.walk(parent_dir):
    roh_files = get_files_with_suffix(root, files, 'ROH.csv')
    if roh_files:
        for roh_file in roh_files:
            data = np.genfromtxt(roh_file, delimiter=',', skip_header=1)
            # more funny calculations
    else:
        rrs_files = get_files_with_suffix(root, files, 'RRS.csv')
        for rrs_file in rrs_files:
            data = np.genfromtxt(rrs_file, delimiter=',', skip_header=1)
            # some calculations

如果计算结果相同,我会将所有代码副本提取到不同的函数:

def give_this_a_better_name_that_explains_the_specific_calculations(filename):
    data = np.genfromtxt(filename, delimiter=',', skip_header=1)
    # some calculations

def get_files_with_suffix(root, files, suffix):
    return [os.path.join(root, filename) for filename in files if filename.endswith(suffix)]

def process_files_with_suffix_but_give_this_a_better_name_too(root, files, suffix):
    files = get_files_with_suffix(root, files, suffix)
    for file in files:
        give_this_a_better_name_that_explains_the_specific_calculations(file)
    return files

for root, dirs, files in os.walk(parent_dir):
    if not process_files_with_suffix_but_give_this_a_better_name_too(root, filename, 'ROH.csv'):
        process_files_with_suffix_but_give_this_a_better_name_too(root, filename, 'RRS.csv')

相关问题 更多 >