Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.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 - Fatal编程技术网

Python 从以特定字符开头的目录中获取文件

Python 从以特定字符开头的目录中获取文件,python,Python,我的路径是c:\testfolder\myfolder\ 在这个文件夹中,我得到了这些文件夹: gr432d4dr fr34q2sf4fd grdddxwes pl34scc us4352fc us4245 gr00mis us994k 这些文件夹中包含cpp文件 我只想从以gr和us开头的文件夹中搜索 以下是我尝试搜索特定文件夹的代码: def search(): for filename in Path('c:\testfolder\myfolder\').glob('**/*.c

我的路径是c:\testfolder\myfolder\

在这个文件夹中,我得到了这些文件夹:

gr432d4dr
fr34q2sf4fd
grdddxwes
pl34scc
us4352fc
us4245
gr00mis
us994k
这些文件夹中包含cpp文件

我只想从以gr和us开头的文件夹中搜索

以下是我尝试搜索特定文件夹的代码:

def search():
    for filename in Path('c:\testfolder\myfolder\').glob('**/*.cpp') :  
        with open(filename) as f:  
            if "gr" or "us" in f:
              #do something
我放了一个打印文件来查看,但似乎它仍在检查所有文件夹

f不是文件名,而是允许您访问文件内容的文件对象资源。在打开文件之前,必须检查文件名

def search():
    for filename in Path(r'c:\testfolder\myfolder\').glob('**/*.cpp') :  
        if "gr" in os.fspath(filename) or "us" in os.fspath(filename):
            with open(filename) as f:  
              #do something
您需要os.fspath从Path对象获取字符串,以便使用in运算符搜索字符串中的子字符串。
还要注意我编辑的if条件。应以这种方式写入。

使用原始字符串r'c:\testfolder\myfolder'避免字符转义。仍然打印所有内容。当我删除我们并只留下“gr”时,会出现以下错误->类型错误:“WindowsPath”类型的参数不可编辑