我有5个文件夹,在其中,我有不同的文件,必须排除以特定字符串开头的文件。我在下面的目录中写的用于打开目录的子文件夹的代码,但是不能排除文件。
yourpath = r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'
import os
import numpy as np
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
#print(os.path.join(root, name))
CASES = [f for f in sorted(os.path.join(root,name)) if f.startswith('config')] #To find the files
maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES]) #Sorting based on numbers
CASES= ['configuration_%d.out' % i for i in range(maxnum)] #Reading sorted files
## Doing My computations
我有点对这行感到困惑:
CASES = [f for f in sorted(os.path.join(root,name)) if f.startswith('config')] #To find the files
您是否要在目录中查找以'config'开头的文件并将其添加到'CASES'列表中?
因为逻辑有些偏离。您正在使用os.path.join创建完整路径,然后检查完整路径'C:...'是否以config开头。最重要的是,您将文件名存储为排序列表。 ['C',':',...]。
您可以简单地说:
if name.startswith('config'):
CASES.append(name)
或
CASES.append(name) if name.startswith('config') else None