Programing

glob 제외 패턴

lottogame 2020. 11. 10. 07:39
반응형

glob 제외 패턴


내부에 eee2314, asd3442... 및 eph.

나는로 시작하는 모든 파일을 제외 할 ephglob기능을.

어떻게하니?


glob의 패턴 규칙은 정규식이 아닙니다. 대신 표준 Unix 경로 확장 규칙을 따릅니다. 특수 문자는 몇 개뿐입니다. 두 개의 서로 다른 와일드 카드 및 문자 범위가 [from glob ] 에서 지원됩니다 .

따라서 패턴이있는 일부 파일을 제외 할 수 있습니다.
예를 들어 _glob으로 매니페스트 파일 (로 시작하는 파일)을 제외 하려면 다음을 사용할 수 있습니다.

files = glob.glob('files_path/[!_]*')

glob함수로 패턴을 제외 할 수 없으며 glob은 포함 패턴 만 허용합니다 . 글 로빙 구문 은 매우 제한적입니다 ( [!..]문자 클래스 문자 와 일치 해야 하므로 클래스에없는 모든 문자에 대한 포함 패턴 입니다).

자체 필터링을 수행해야합니다. 목록 이해는 일반적으로 여기에서 잘 작동합니다.

files = [fn for fn in glob('somepath/*.txt') 
         if not os.path.basename(fn).startswith('eph')]

세트를 공제 할 수 있습니다.

set(glob("*")) - set(glob("eph*"))

게임이 늦었지만 filter결과에 파이썬 적용 할 수도 있습니다 glob.

files = glob.iglob('your_path_here')
files_i_care_about = filter(lambda x: not x.startswith("eph"), files)

또는 람다를 적절한 정규식 검색 등으로 대체합니다.

편집 : 전체 경로를 사용하는 경우 startswith작동하지 않으므로 정규식이 필요 하다는 것을 깨달았습니다.

In [10]: a
Out[10]: ['/some/path/foo', 'some/path/bar', 'some/path/eph_thing']

In [11]: filter(lambda x: not re.search('/eph', x), a)
Out[11]: ['/some/path/foo', 'some/path/bar']

보다 일반적으로 일부 쉘 정규식을 준수하지 않는 파일을 제외하려면 module을 사용할 수 있습니다 fnmatch.

import fnmatch

file_list = glob('somepath')    
for ind, ii in enumerate(file_list):
    if not fnmatch.fnmatch(ii, 'bash_regexp_with_exclude'):
        file_list.pop(ind)

위의 방법은 먼저 주어진 경로에서 목록을 생성 한 다음 원하는 제약 조건으로 정규식을 충족하지 않는 파일을 표시합니다.


와 비교 glob내가 추천, pathlib필터, 하나 개의 패턴은 매우 간단합니다.

from pathlib import Path
p = Path(YOUR_PATH)
filtered = [x for x in p.glob('**/*') if not x.name.startswith('eph'))]

더 복잡한 패턴을 필터링하려면 다음과 같이이를 수행하는 함수를 정의 할 수 있습니다.

def not_in_pattern(x):
    return (not x.name.startswith('eph')) and 
            not x.name.startswith('epi')'))

filtered = [x for x in p.glob('**/*') if not_in_pattern(x)]

이 코드를 사용하면로 시작 eph하거나로 시작 하는 모든 파일을 필터링 할 수 있습니다 epi.


폴더의 모든 파일을 반복하면서 특정 파일을 건너 뛰는 것은 어떻습니까! 아래 코드는 'eph'로 시작하는 모든 Excel 파일을 건너 뜁니다.

import glob
import re
for file in glob.glob('*.xlsx'):
    if re.match('eph.*\.xlsx',file):
        continue
    else:
        #do your stuff here
        print(file)

이렇게하면 더 복잡한 정규식 패턴을 사용하여 특정 파일 집합을 폴더에 포함 / 제외 할 수 있습니다.


As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)


You can use the below method:

# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
    if file not in ephFiles:
        noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.

Thank you.  

참고URL : https://stackoverflow.com/questions/20638040/glob-exclude-pattern

반응형