Python 如何在执行多次读取时排除目录?

Python 如何在执行多次读取时排除目录?,python,python-3.x,Python,Python 3.x,我是python的初学者,我试图通过一个路径读取目录和子目录中的所有文件,并将相关文件合并到一个文件中。同时,我想排除一些特定的子目录,我被困在这一步。感谢专家们的帮助 这里有一些细节 主要路径: /usr/home/micro/**/*.txt 要跳过的子目录: /usr/home/micro/frame/test 到目前为止,我的Python代码 只需跳过以路径开头的名称: def test(): with open("results.txt", "w") as f:

我是python的初学者,我试图通过一个路径读取目录和子目录中的所有文件,并将相关文件合并到一个文件中。同时,我想排除一些特定的子目录,我被困在这一步。感谢专家们的帮助

这里有一些细节

主要路径:

/usr/home/micro/**/*.txt
要跳过的子目录:

 /usr/home/micro/frame/test
到目前为止,我的Python代码



只需跳过以路径开头的名称:

def test():
    with open("results.txt", "w") as f:
        for name in complete:
            if name.startswith("/usr/home/micro/frame/test"):
                continue
            with open(name) as currentfile:
                current = currentfile.read()
                    f.write(current)

无需
os.walk
如果已经在美国
glob.glob

则要跳过的目录名似乎位于“/usr/home/micro/frame/test”文件中。然后,您需要将此文件读取到列表并使用该列表:

with open("skipfilenames.txt", "r") as f:
    skiplist = f.read().splitlines()
然后您可以使用:

for skipped in skiplist:
...
在(“/usr/home/micro/frame/test”)中跳过的
行的功能与您认为的不同。它不是在元组上迭代,而是在单个路径的字符上迭代

您需要在括号末尾前加一个逗号,使其成为元组:
(“/usr/home/micro/frame/test”)
。没有逗号,括号只是一个不必要的操作顺序提示(比如
(2*2)+1
2*2+1
是如何相同的)。或者,如果只需要排除一条路径,则可以完全消除循环

这不会自行修复代码,因为在
os.walk
循环中,除了尝试排除不需要的文件夹之外,实际上没有做任何有用的事情。但是,如果您在
complete
上摆脱循环,并使用
os.walk
中的
文件
iterable,您就可以做我认为您想做的事情

试着这样做:

def test():
    with open("results.txt", "w") as f:
        for root, dirs, files in os.walk("/usr/home/micro/frame/"):   # get rid of first loop
            for skipped in ("/usr/home/micro/frame/test",):       # add comma to make a tuple
                if skipped in dirs:
                    dirs.remove(skipped)
            for name in files:           # move the rest of the logic inside the os.walk loop
                fullname = os.path.join(root, name)
                with open(fullname) as currentfile:
                    current = currentfile.read()
                f.write(current)

这工作得很好,实现起来也很简单。谢谢各位专家的帮助!!
def test():
    with open("results.txt", "w") as f:
        for root, dirs, files in os.walk("/usr/home/micro/frame/"):   # get rid of first loop
            for skipped in ("/usr/home/micro/frame/test",):       # add comma to make a tuple
                if skipped in dirs:
                    dirs.remove(skipped)
            for name in files:           # move the rest of the logic inside the os.walk loop
                fullname = os.path.join(root, name)
                with open(fullname) as currentfile:
                    current = currentfile.read()
                f.write(current)