我有以下情况要解决:我的父目录有〜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'结尾,而不是每个文件是否都以'ROH.csv'结尾。 (ii)我还没有找到指定要加载哪个文件的方法; endswith不起作用(布尔); (iii)包含两个for循环。
希望任何人都有解决此问题的想法。
答案 0 :(得分:0)
我不太确定我是否理解您提到的问题,但是下面的代码片段为您提供了要处理的文件列表。您可以以更聪明或更易读的方式更改过滤条件,但是我已经使用一层嵌套文件夹对其进行了测试,并且可以完成此工作。您可以从这里开始确定更清晰或更适合您需求的内容
#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)
答案 1 :(得分:0)
这是假设您需要对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')