Python 将 "met conditional value" 移出循环
Python move "met conditional value" outside of loop
这可能令人困惑。
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
迭代之间。
我一直在尝试不同的嵌套方法,但我缺乏基本的循环构造逻辑。
感谢任何帮助,谢谢!
编辑:
我正在遍历主目录,并将所有父文件夹写入文本文件。我想在每个父文件夹之间写下它的子文件夹:即如果父文件夹包含更多文件夹,则将这些文件夹写在每个父文件夹之间;如果父文件夹不包含更多文件夹,则跳到下一个父文件夹等。为每个步骤编写函数。
我正在尝试以特定格式编写文件夹的名称,具体取决于它们是一级子目录、二级子目录等...
我想要的:
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.walk 或遍历目录。我已经写了很多代码,我希望重点回答我关于 运行 条件循环并将该循环中的值放入另一个循环中的写入函数的问题。
我更愿意重构这个循环逻辑,而不是重新开始整个 os.walk for 循环。
再次感谢
我不太确定您所说的术语 "conditional loop" 是什么意思,但是使用基于 os.listdir
的小型递归函数可以轻松实现您想要实现的目标。您 可以 使用 os.walk
执行此操作,但我经常发现显式调用 os.listdir
更简单(也更有效)(os.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)
'file.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')
这可能令人困惑。
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
迭代之间。
我一直在尝试不同的嵌套方法,但我缺乏基本的循环构造逻辑。
感谢任何帮助,谢谢!
编辑:
我正在遍历主目录,并将所有父文件夹写入文本文件。我想在每个父文件夹之间写下它的子文件夹:即如果父文件夹包含更多文件夹,则将这些文件夹写在每个父文件夹之间;如果父文件夹不包含更多文件夹,则跳到下一个父文件夹等。为每个步骤编写函数。
我正在尝试以特定格式编写文件夹的名称,具体取决于它们是一级子目录、二级子目录等...
我想要的:
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.walk 或遍历目录。我已经写了很多代码,我希望重点回答我关于 运行 条件循环并将该循环中的值放入另一个循环中的写入函数的问题。
我更愿意重构这个循环逻辑,而不是重新开始整个 os.walk for 循环。
再次感谢
我不太确定您所说的术语 "conditional loop" 是什么意思,但是使用基于 os.listdir
的小型递归函数可以轻松实现您想要实现的目标。您 可以 使用 os.walk
执行此操作,但我经常发现显式调用 os.listdir
更简单(也更有效)(os.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)
'file.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')