Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用文本文件中的元素准确搜索目录?_Python_Regex_Python 3.x - Fatal编程技术网

Python 如何使用文本文件中的元素准确搜索目录?

Python 如何使用文本文件中的元素准确搜索目录?,python,regex,python-3.x,Python,Regex,Python 3.x,对python来说相当新鲜。我正在尝试使用一个文本文件列表来搜索目录中的文件和文件夹。它在一定程度上起作用,但仅当我使用.startswith()时,搜索元素位于文件/文件夹名称的开头 下面是我正在使用的代码 我想regex可能是一个不错的选择,但似乎无法理解 谢谢你的帮助 谢谢 import os def data_cleansing(path): dirscount = 0 filescount = 0 with open("Y:\Admin\Data Cle

对python来说相当新鲜。我正在尝试使用一个文本文件列表来搜索目录中的文件和文件夹。它在一定程度上起作用,但仅当我使用.startswith()时,搜索元素位于文件/文件夹名称的开头

下面是我正在使用的代码

我想regex可能是一个不错的选择,但似乎无法理解

谢谢你的帮助

谢谢

import os

def data_cleansing(path):

    dirscount = 0
    filescount = 0


    with open("Y:\Admin\Data Cleansing\DCList.txt","r") as f:
        x = f.readlines()
        x = [x.replace("\n","") for x in x]

    #print(x)


    for root, dirs, files in os.walk(path):
        for dirs in dirs:
            if dirs.startswith(tuple(x)):
                dirscount = dirscount + 1
                #print(dirscount)
                print(os.path.join(dirs))



    for root, dirs, files in os.walk(path):
        for files in files:
            if files.startswith(tuple(x)):
                filescount = filescount + 1
                #print(filescount)
                print(os.path.join(files))



    total = (dirscount + filescount)
    print(total,"files and folders found in",path,"that need cleansing.")

data_cleansing(r"G:\Processed\failed")
print("*"*70)
data_cleansing(r"G:\Processed\done")
print("*"*70)
data_cleansing(r"S:\Prosort")
print("*"*70)
data_cleansing(r"S:\Prosort_Archive")

这符合你的需要吗

from os import scandir
find_list = ['Uni', '.doc', 'XML']
path = r"c:\\Autoit\\ForumTests\\"

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)
        else:
            yield entry

if __name__ == '__main__':
    for entry in scantree(path):
        for pattern in find_list:
            if pattern in entry.path:
                print(pattern, '-->', entry.path)

如果
.startswith()
不起作用,请不要使用它。你试过操作符了吗?根据你的困境,有哪些输入和它们想要的输出?搜索列表中的一个元素是“MT19”,要搜索的目录有一个名为“MT19CORE”或XXXXMT19的文件夹,如果python能“找到”任何“MT19”的实例,我会很高兴。谢谢你的回复。我正在尝试使用一个文本文件列表来搜索目录中的文件和文件夹。列表/文件是什么样子的?请参阅:。