Listing files in a directory that does not match the template

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

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

How to select other files that DO NOT start with "hello"?

+4
source share
3 answers

According to the documentationglob module , it works with os.listdir () and fnmatch.fnmatch () functions in concert, and does not actually invoke a subshell.

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

import fnmatch
import os

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

Hope this helps.

+2
source

How to use only the globe:

:

>>> glob.glob('*')
['fee.py', 'foo.py', 'hello.txt', 'hello1.txt', 'test.txt', 'text.txt']
>>>

hello.txt:

>>> glob.glob('hello*.txt')
['hello.txt', 'hello1.txt']
>>>

hello:

>>> glob.glob('[!hello]*')
['fee.py', 'foo.py', 'test.txt', 'text.txt']
>>>

hello, .txt:

>>> glob.glob('[!hello]*.txt')
['test.txt', 'text.txt']
>>>
+6

You can simply map all the files using a template "*", and then sift out those that you are not interested in, for example:

from glob import glob
from fnmatch import fnmatch

files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
0
source

Source: https://habr.com/ru/post/1533270/


All Articles