相关疑难解决方法(0)

过滤os.walk()目录和文件

我正在寻找一种方法来包含/排除文件模式并从os.walk()调用中排除目录.

这就是我现在正在做的事情:

import fnmatch
import os

includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']

def _filter(paths):
    matches = []

    for path in paths:
        append = None

        for include in includes:
            if os.path.isdir(path):
                append = True
                break

            if fnmatch.fnmatch(path, include):
                append = True
                break

        for exclude in excludes:
            if os.path.isdir(path) and path == exclude:
                append = False
                break

            if fnmatch.fnmatch(path, exclude):
                append = False
                break

        if append:
            matches.append(path)

    return matches

for root, dirs, files in os.walk('/home/paulo-freitas'):
    dirs[:] = _filter(map(lambda d: …
Run Code Online (Sandbox Code Playgroud)

python filtering os.walk

41
推荐指数
3
解决办法
8万
查看次数

用Python替换文件中的字符串

如何在给定目录及其子目录中递归替换给定替换的匹配?

伪代码

import os
import re
from os.path import walk
for root, dirs, files in os.walk("/home/noa/Desktop/codes"):
        for name in dirs:
                re.search("dbname=noa user=noa", "dbname=masi user=masi")
                   // I am trying to replace here a given match in a file
Run Code Online (Sandbox Code Playgroud)

python regex search operating-system replace

13
推荐指数
2
解决办法
2万
查看次数

os.walk与正则表达式

我想获得一个适用于我所拥有的正则表达式的文件列表.我想我应该使用os.walk,但我如何使用正则表达式?

谢谢.

python regex os.walk

2
推荐指数
2
解决办法
4252
查看次数

标签 统计

python ×3

os.walk ×2

regex ×2

filtering ×1

operating-system ×1

replace ×1

search ×1