这可能令人困惑。你知道吗
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循环。你知道吗
再次感谢
我不太清楚你所说的“条件循环”是什么意思,但是你想要实现的是使用一个基于
os.listdir
的小递归函数。您可以使用os.walk
来实现这一点,但我经常发现显式调用os.listdir
(os.walk
在内部调用os.listdir
)更简单(更有效),尤其是当您不需要单独的目录和普通文件列表时。你知道吗内容'文件.txt'
一般来说,在Python中避免递归比较好,如果可行的话:Python解释器不能执行tail call elimination,并且它会施加最大的递归深度。但是,在处理递归数据结构(如文件树)时,使用递归算法是很自然的。你知道吗
FWIW,下面的代码迭代地执行上面代码的逆操作;我使用它从问题中给出的目录名缩进列表中构建目录树。你知道吗
相关问题 更多 >
编程相关推荐