列出目录中不匹配模式的文件 [英] Listing files in a directory not matching pattern

查看:76
本文介绍了列出目录中不匹配模式的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码列出了以"hello"开头的目录中的所有文件:

The following code lists down all the files in a directory beginning with "hello":

import glob
files = glob.glob("hello*.txt")

如何选择不是以"hello"开头的其他文件?

How can I select other files that ARE NOT beginning with "hello"?

推荐答案

根据glob模块的文档,它可以通过使用 os.listdir() fnmatch.fnmatch()函数演唱会,而不是实际调用子shell.

According to glob module's documentation, it works by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.

os.listdir()返回指定目录中的条目列表,而fnmatch.fnmatch()为您提供unix shell样式的通配符,请使用它:

os.listdir() returns you a list of entries in the specified directory, and fnmatch.fnmatch() provides you with unix shell-style wildcards, use it:

import fnmatch
import os

for file in os.listdir('.'):
    if not fnmatch.fnmatch(file, 'hello*.txt'):
        print file

希望有帮助.

这篇关于列出目录中不匹配模式的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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