简体   繁体   English

Python:os.walk到特定的目录和文件

[英]Python: os.walk to specific directory and file

I have a file structure that looks like: 我有一个文件结构,如下所示:

|num_1

|----|dir1

|--------|dir2

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

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

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

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

|num_2

|----|dir1

|--------|dcm

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

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

|num_n

I want to us os.walk (or something more appropriate?) to traverse the tree until it finds the directory "dcm". 我想要os.walk(或更合适的东西?)来遍历树,直到找到目录“dcm”。 dcm can be at varying levels of the tree dcm可以处于树的不同级别

This is what I have. 这就是我所拥有的。 Thanks! 谢谢!

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)

I went ahead with the "lazy" way and used listdir to read out all of the files under the dcm directory - decided that the resource cost wasn't too high. 我继续使用“懒惰”方式并使用listdir读出dcm目录下的所有文件 - 确定资源成本不是太高。 That being said, I think that pulling out a single random file from a directory without reading all of those files is an interesting query that someone more Python oriented than I should answer! 话虽这么说,我认为从一个目录中取出一个随机文件而不读取所有这些文件是一个有趣的查询,有人比我应该回答的更多的Python!

For reference, my final solution was... do excuse the inefficiencies in iterator usage! 作为参考,我的最终解决方案是......请原谅迭代器使用效率低下! I am new and needed a quick solution 我是新手,需要快速解决方案

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]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM