制作os.步行不规范工作

2024-04-25 14:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着按以下顺序做:

使用os.walk()向下搜索每个目录。
每个目录都有subfolders,但我只对第一个subfolder感兴趣。所以目录看起来像:

/home/RawData/SubFolder1/SubFolder2

例如。在RawData2中,我希望文件夹停止在子文件夹1级别。你知道吗

问题是,似乎os.walk()遍历了所有RawData文件夹,我不确定如何停止。你知道吗

下面是我到目前为止所做的-我尝试过用变量dir替换根目录或文件的其他组合,但这似乎并没有得到我想要的。你知道吗

import os 

for root, dirs, files in os.walk("/home/RawData"): 

    os.chdir("/home/RawData2/")
    make_path("/home/RawData2/"+str(dirs))

Tags: 目录文件夹home顺序os级别感兴趣walk
2条回答

我建议你改用glob。你知道吗

正如glob上的帮助所描述的:

glob(pathname)
    Return a list of paths matching a pathname pattern.

    The pattern may contain simple shell-style wildcards a la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

所以,你的模式是每一个一级目录,我想应该是这样的:

/root_path/*/sub_folder1/sub_folder2

所以,你从你的根开始,把所有东西都放在第一层,然后寻找sub_folder1/sub_folder2。我认为这很管用。你知道吗

总而言之:

from glob import glob

dirs = glob('/root_path/*/sub_folder1/sub_folder2')

# Then iterate for each path
for i in dirs:
    print(i)

小心os.walk的文档说明:

don’t change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn’t either

所以您应该避免在walk循环中使用os.chdir("/home/RawData2/")。你知道吗

通过使用topdown=True并清除dirs,您可以很容易地要求walk不要递归:

for root, dirs, files in os.walk("/home/RawData", True):
    for rep in dirs:
        make_path(os.join("/home/RawData2/", rep )
        # add processing here
    del dirs[]  # tell walk not to recurse in any sub directory

相关问题 更多 >