Python 如何使用os.walk从特定文件夹中的特定文件访问信息

Python 如何使用os.walk从特定文件夹中的特定文件访问信息,python,Python,这个问题扩展了我之前的问题,我对代码还有另一个问题。我试着在我上一个问题的编辑版本中发布这个问题,但没有引起注意。我再说一遍: 新增问题: 我得到了第一个问题的答案,现在我有了另一个问题。在根目录下的目录中有许多子目录。我只想访问所有目录中具有相同名称的一个子目录中的信息。这就是我所尝试的: for root, dirs, files in os.walk("/rootPath/"): for dname in dirs: #print dname, type(dname)

这个问题扩展了我之前的问题,我对代码还有另一个问题。我试着在我上一个问题的编辑版本中发布这个问题,但没有引起注意。我再说一遍:

新增问题:

我得到了第一个问题的答案,现在我有了另一个问题。在根目录下的目录中有许多子目录。我只想访问所有目录中具有相同名称的一个子目录中的信息。这就是我所尝试的:

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”结尾的子目录

我不是百分之百肯定我能理解你的问题。我假设您希望对每个
code\u输出
子目录中以字符串
sumAll.txt
结尾的所有文件进行操作

如果是这种情况,那么您可以简单地去掉第二个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)