2014-01-29 2 views
1

이 질문은 이전 질문에서 확장됩니다. 코드에 다른 문제가 있습니다. 나는 나의 마지막 질문의 편집 된 버전에이 질문을 게시하려했지만 주목을받지 못했다. 그래서 여기에 다시 이동합니다os.walk을 사용하여 특정 폴더의 특정 파일에서 정보에 액세스하는 방법

ADDED 문제 :

내가 내 첫 번째 질문에 대한 대답을 얻었다, 지금은 또 다른 있습니다. 루트 아래의 디렉토리에는 많은 하위 디렉토리가 있습니다. 모든 디렉토리에서 동일한 이름을 가진 하나의 하위 디렉토리에서만 정보에 액세스하려고합니다.

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'엔딩 않습니다 이것은 내가 뭘하려?

답변

1

100 % 확신 할 수없는 질문입니다. 각 code_output 하위 디렉토리에 문자열 sumAll.txt으로 끝나는 모든 파일을 처리하려고한다고 가정합니다.

그 다음 당신은 단순히 루프 두 번째 제거 할 수있는 경우라면 :

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) 
관련 문제