2014-01-29 80 views
1

這個問題擴展了我之前的問題,我還遇到了另一個代碼問題。我試圖在我最後一個問題的編輯版本中發佈這個問題,但它沒有被注意到。所以在這裏,我又來了:如何使用os.walk訪問特定文件夾中特定文件的信息

額外的問題:

我的回答得到了我的第一個問題,我現在有另一個。在根目錄下的目錄中有許多子目錄。我想只從一個在所有目錄中具有相同名稱的子目錄訪問信息。這是我的嘗試:

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循環:

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) 
相關問題