2017-03-29 9 views
1

は私が見えファイル構造を持つファイル:私はそれを見つけるまでツリーを走査するために私達os.walk(?またはより適切なもの)にしたいPythonの:特定のディレクトリにos.walkなど

|num_1 

|----|dir1 

|--------|dir2 

|------------|dcm 

|----------------\file_1 

|----------------\file_2 

|----------------\file_n 

|num_2 

|----|dir1 

|--------|dcm 

|------------\file_1 

|------------\file_n 

|num_n 

ディレクトリ "dcm"。 dcmはさまざまなレベルのツリーにあります。

これは私が持っているものです。ありがとう!

import dicom 
import re 
import os 

dcm = [] 
PATH = "C:\foo" 

#find the directory we want to get to, save path 
for path, dirs in os.walk(PATH): 
    for dirname in dirs: 
     fullpath = os.path.join(path,dirname) 
     if "dcm" in dirname: 
      #copied this first_file line - just want a fast and easy way to grab ONE file in the dcm directory 
      #without reading any of the others (for time reasons) 
      first_file = next((join(path, f) for f in os.listdir(path) if isfile(join(path, f))),"none") 
      fullpath = os.path.join(fullpath,first_file) 
      dcm.append(fullpath) 

答えて

0

私はDCMディレクトリの下のすべてのファイルを読み出すために「怠惰」な方法と使用LISTDIRを進めて行きました - リソースのコストが高すぎないと判断しました。 それは、私はそれらのファイルのすべてを読まずにディレクトリから一つのランダムなファイルを抜き出すことは、私が答えなければならないよりもPythonの方が向いている興味深い質問だと思います!

参考までに、私の最終的な解決策は...イテレータ使用の非効率性を言い訳にしてください!私は新しく、迅速な解決が必要でした。

for path, dirs, filename in os.walk(rootDir): #omit files, loop through later 
    for dirname in dirs: 
     fullpath = os.path.join(path,dirname) 
     if "dcm" in dirname: 
      dcm.append(fullpath) 

final = [] 
uni = 0 
final.append(dcm[0]) 
for i in range(len(dcm)): 
    if len(os.listdir(dcm[i])) < 10: 
     pass 
    elif dcm[i][16:19] != final[uni][16:19]: 
     final.append(dcm[i]) 
     uni += 1 


tags = ((0x8, 0x70)),((0x8, 0x1090)), ((0x18, 0x1020)) 
values = [] 
printout = [] 
for p in range(len(final)): 
    file = os.path.join(final[p],os.listdir(final[p])[0]) 
    ds = dicom.read_file(file) 
    printout.append([final[p]]) 
    for k in range(len(tags)): 
     printout.append([ds[tags[k]]]) 
関連する問題