在部分字符串匹配的目录中查找文件 [英] Find files in a directory with a partial string match

查看:78
本文介绍了在部分字符串匹配的目录中查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下文件的目录:

I have a directory which contains the following files:

apple1.json.gz
apple2.json.gz
banana1.json.gz
melon1.json.gz
melon2.json.gz

我希望找到所有applebananamelon文件类型.

I wish to find all of the apple, banana and melon file types.

从此 SO答案知道我可以通过以下文件类型来查找:

From this SO answer I know that I can find by file type by:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.json.gz"):
    print(file)

但是,就我而言,我无法按文件名或文件类型进行匹配.而是部分文件名匹配(所有apple依此类推)

However, in my case I can't match by file name or file type. Rather it is a partial file name match (all apple's and so on)

在此 SO问题中,提出了该解决方案:

In this SO question, this solution was proposed:

[in] for file in glob.glob('/path/apple*.json.gz'):
    print file

但是,它返回零

[out]
     0

推荐答案

在文件/mydir中具有以下内容

mydir
├── apple1.json.gz
├── apple2.json.gz
├── banana1.json.gz
├── melon1.json.gz
└── melon2.json.gz

你可以做

import glob
import os

os.chdir('/mydir')
for file in glob.glob('apple*.json.gz'):
    print file

import glob

for file in glob.glob('/mydir/apple*.json.gz'):
    print file

更改目录不会影响glob.glob('/absolute/path').

这篇关于在部分字符串匹配的目录中查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆