简体   繁体   English

Python:os.chdir()在for循环中不起作用?

[英]Python: os.chdir() not working within a for loop?

I'm trying to get a homemade path navigation function working - basically I need to go through one folder, and explore every folder within it, running a function within each folder. 我正在尝试使用自制的路径导航功能-基本上,我需要浏览一个文件夹,浏览其中的每个文件夹,并在每个文件夹中运行一个功能。

I reach a problem when I try to change directories within a for loop. 当我尝试在for循环中更改目录时,我遇到了问题。 I've got this "findDirectories" function: 我有这个“findDirectories”功能:

def findDirectories(list):
    for files in os.listdir("."):
        print (files)
        list.append(files)
        os.chdir("y")

That last line causes the problems. 最后一行导致了问题。 If I remove it, the function just compiles a list with all the folders in that folder. 如果删除它,该函数只会编译包含该文件夹中所有文件夹的列表。 Unfortunately, this means I have to run this each time I go down a folder, I can't just run the whole thing once. 不幸的是,这意味着我每次下载文件夹时都必须运行它,我不能只运行一次。 I've specified the folder "y" as that's a real folder, but the program crashes upon opening even with that. 我已将文件夹“y”指定为真正的文件夹,但即使这样,程序也会在打开时崩溃。 Doing os.chdir("y") outside of the for loop has no issues at all. 在for循环之外执行os.chdir(“ y”)完全没有问题。

I'm new to Python, but not to programming in general. 我是Python的新手,但不是一般的编程。 How can I get this to work, or is there a better way? 我怎样才能让它发挥作用,或者有更好的方法吗? The final result I need is running a Function on each single "*Response.xml" file that exists within this folder, no matter how deeply nested it is. 我需要的最终结果是,无论该文件夹有多深嵌套,都在此文件夹中存在的每个“ * Response.xml”文件上运行一个Function。

Well, you don't post the traceback of the actual error but clearly it doesn't work as you have specified y as a relative path. 好吧,你不发布实际错误的追溯,但显然它不起作用,因为你已指定y作为相对路径。

Thus it may be able to change to y in the first iteration of the loop, but in the second it will be trying to change to a subdirectory of y that is also called y 因此它可能能够在循环的第一次迭代中更改为y ,但在第二次迭代中它将尝试更改为y子目录 ,也称为y

Which you probably do not have. 你可能没有。

You want to be doing something like 你想做类似的事情

import os

for dirName, subDirs, fileNames in os.walk(rootPath):
    # its not clear which files you want, I assume anything that ends with Response.xml?
    for f in fileNames:
        if f.endswith("Response.xml"):
            # this is the path you will want to use
            filePath = os.path.join(dirName, f)

            # now do something with it!
            doSomethingWithFilePath(filePath)

Thats untested, but you have the idea ... 多数民众赞成未经测试,但你有主意...

As Dan said, os.walk would be better. 正如Dan所说, os.walk会更好。 See the example there. 参见那里的例子。

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

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