这个问题扩展了我之前的问题,我的代码还有另外一个问题。我试着在我上一期的问题的编辑版本中发布这个问题,但它没有被注意到。所以我再来一次:
添加问题:
我得到了第一个问题的答案,现在我有了另一个问题。在根目录下的目录中有许多子目录。我想从所有目录中只有一个具有相同名称的子目录访问信息。这就是我试过的:
for root, dirs, files in os.walk("/rootPath/"):
for dname in dirs:
#print dname, type(dname)
allPIs = []
allDirs = []
if dname.endswith('code_output'): #I only want to access information from one file in sub-directories with this name
ofh = open("sumPIs.txt", 'w')
ofh.write("path\tPIs_mean\n")
for fname in files: #Here i want to be in the code_output sub-directory
print fname #here I only want to see files in the sub-directory with the 'code_output' end of a name, but I get all files in the directory AND sub-directory
if fname.endswith('sumAll.txt'):
PIs = []
with open(os.path.join(root,fname), 'r') as fh_in:
for line in fh_in:
line = line.rstrip()
line = line.split('\t')
PIs.append(int(line[2]))
PIs_mean = numpy.mean(PIs)
allPIs.append(PIs_mean)
allDirs.append(filePath)
为什么这会循环遍历目录中的所有文件而不仅仅是名称以'code_output'结尾的子目录?
答案 0 :(得分:1)
我不是100%肯定我得到你的问题。我假设您要对每个sumAll.txt
子目录中以字符串code_output
结尾的所有文件进行操作。
如果是这种情况,那么你可以简单地摆脱第二个for循环:
for root, dirs, files in os.walk("/rootPath/"):
if root.endswith('code_output'):
allPIs = []
allDirs = []
# Create sumPIs.txt in /rootPath/.../code_output
ofh = open("sumPIs.txt", 'w')
ofh.write("path\tPIs_mean\n")
# Iterate over all files in /rootPath/.../code_output
for fname in files:
print fname
if fname.endswith('sumAll.txt'):
PIs = []
with open(os.path.join(root, fname), 'r') as fh_in:
for line in fh_in:
line = line.rstrip()
line = line.split('\t')
PIs.append(int(line[2]))
PIs_mean = numpy.mean(PIs)
allPIs.append(PIs_mean)
allDirs.append(filePath)