Python将“met conditional value”移出循环

2024-09-26 18:01:39 发布

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

这可能令人困惑。你知道吗

rootdir= C:\User\Desktop\File
file = 'file.txt'

mainLocNum = str(list(rootdir)).count(r'\\')
mainFolder=os.listdir(rootdir)

with open(file,'w') as f:

    for dir, subdirs, files in os.walk(rootdir):
        currentDirLevel=str(list(dir)).count(r'\\')
        for allFolders in subdirs:
            if (currentDirLevel - mainLocNum) == 0:
                parentFolders=allFolders
                f.write(str(parentFolders))
                PLACEHOLDER
            elif (currentDirLevel - mainLocNum) == 1:
                subFolders=allFolders
                f.write(str(allFolders)     <----- write this in PLACEHOLDER

我只想在满足elif条件的情况下,将第二条write语句写入PLACEHOLDER行。如果我不在PLACEHOLDER位置写第二个write语句,第二个条件中的第二个write语句写在文本文件的最底部;但是我想在PLACEHOLDER位置写第二个条件的write语句(仅当它满足时),它位于第一次write迭代之间。你知道吗

我一直在尝试不同的嵌套方法,但我缺乏基本的循环构造逻辑。你知道吗

感谢您的帮助,谢谢!你知道吗

编辑:

我在主目录中循环,并将所有父文件夹写入文本文件。我想在每个父文件夹及其子文件夹之间写入:即如果父文件夹包含更多文件夹,则在每个父文件夹之间写入这些文件夹;如果父文件夹不包含更多文件夹,跳到下一个父文件夹等。我使用if(currentDirLevel-mainLocNum)=(number)来知道它要进入多少个目录,并为每个步骤执行不同的写入功能。你知道吗

我试图写在某些格式的文件夹名称取决于他们是否是一级子目录,二级子目录等。。。你知道吗

我想要的是:

ParentFolder1
    SubFolder1
    Subfolder2
        SubSubFolder1
    SubFolder3
ParentFolder2
    SubFolder1
ParentFolder3
ParentFolder4
    SubFolder1
        SubSubFolder1
            SubSubSubFolder1
        SubSubFolder2
    SubFolder2
ParentFolder5
    SubFolder1

我得到了什么

ParentFolder1
ParentFolder2
ParentFolder3
ParentFolder4
ParentFolder5
SubFolder1
SubFolder2
SubFolder3
SubFolder1
SubFolder1
SubFolder2
SubFolder1
SubSubFolder1
SubSubFolder1
SubSubFolder2
SubSubSubFolder1

请不要把注意力集中在os.步行或者遍历目录。我已经编写了很多代码,我希望主要的焦点能够回答我关于运行条件循环并将该循环中的值放入另一个循环中的write函数的问题。你知道吗

我更喜欢重构这个循环逻辑,而不是从整体开始os.步行for循环。你知道吗

再次感谢


Tags: 文件夹foros语句条件placeholderfilewrite
1条回答
网友
1楼 · 发布于 2024-09-26 18:01:39

我不太清楚你所说的“条件循环”是什么意思,但是你想要实现的是使用一个基于os.listdir的小递归函数。您可以使用os.walk来实现这一点,但我经常发现显式调用os.listdiros.walk在内部调用os.listdir)更简单(更有效),尤其是当您不需要单独的目录和普通文件列表时。你知道吗

import os

tab = 4 * ' '

def writedirs(fhandle, path, depth=0):
    ''' Recursively walk the directory tree starting at path,
        writing all directory names to open file handle fhandle.
        Nodes are traversed depth-first, top-down, and names
        are indented proportional to their depth.
    '''
    data = os.listdir(path)
    # Names returned by listdir are in file system order;
    # If you want them sorted alphabetically, call
    # data.sort()
    # or
    # data.sort(key=str.lower)
    # for case-insensitive sorting.

    indent = depth * tab
    depth += 1
    for filename in data:
        fullpath = os.path.join(path, filename)
        if os.path.isdir(fullpath):
            fhandle.write(indent + filename + '\n')
            writedirs(fhandle, fullpath, depth)

#Test
rootdir = 'testfolder'
outname = 'file.txt'
with open(outname, 'w') as fhandle:
    writedirs(fhandle, rootdir)

内容'文件.txt'

ParentFolder1
    SubFolder1
    Subfolder2
        SubSubFolder1
    SubFolder3
ParentFolder2
    SubFolder1
ParentFolder3
ParentFolder4
    SubFolder1
        SubSubFolder1
            SubSubSubFolder1
        SubSubFolder2
    SubFolder2
ParentFolder5
    SubFolder1

一般来说,在Python中避免递归比较好,如果可行的话:Python解释器不能执行tail call elimination,并且它会施加最大的递归深度。但是,在处理递归数据结构(如文件树)时,使用递归算法是很自然的。你知道吗


FWIW,下面的代码迭代地执行上面代码的逆操作;我使用它从问题中给出的目录名缩进列表中构建目录树。你知道吗

import os

data = '''
ParentFolder1
    SubFolder1
    Subfolder2
        SubSubFolder1
    SubFolder3
ParentFolder2
    SubFolder1
ParentFolder3
ParentFolder4
    SubFolder1
        SubSubFolder1
            SubSubSubFolder1
        SubSubFolder2
    SubFolder2
ParentFolder5
    SubFolder1
'''[1:]

def show(seq):
    for row in seq:
        print(row)
    print()

def stripcount(s):
    z = s.lstrip(' ')
    count = len(s) - len(z)
    return z, count

joinpath = os.path.join

def make_dir_tree(dir_tree, root=''):
    ''' Create a directory tree in root from dir_tree,
        which is a list of indented directory names.
    '''
    dir_tree = [stripcount(s) for s in dir_tree]
    #show(dir_tree)

    stack = [root]
    depth = -1
    for dname, count in dir_tree:
        if count > depth:
            depth = count
            stack.append(dname)
        elif count < depth:
            depth = count
            stack.pop()
            stack[-1] = dname
        else:
            stack[-1] = dname

        pathname = joinpath(*stack)
        print(pathname)
        os.mkdir(pathname)


dir_tree = data.splitlines()
show(dir_tree)
make_dir_tree(dir_tree, 'testfolder')

相关问题 更多 >

    热门问题