2017-12-13 6 views
1

폴더에서 패턴 목록을 거의 건드리지 만 필터링 된 파일을 가져 오려고합니다.폴더의 필터링 된 파일 목록을 얻는 방법

내 초기 접근 방식은 glob로했다 :

난에 (만 파일 이름) 상대를 원하면서 절대 경로를 반환하는 사실을 제외하고을 예상대로 거의 작동
list_files2 = os.listdir(accordingto) 
movable = set() 
n = 0 
for f in list_files2: 
    name, ext = os.path.splitext(f) 
    name = name.rsplit("_", 1)[0] 
    movable.add(name) 
for m in movable: 
    family = glob("{}{}*".format(dir, m)) 
    for f in family: 
     # f is absolute path and needs to be relative 
     shutil.move(f, target+f) # <- problem is here 
     n += 1 

그것을 대상 폴더에 추가하십시오.

나는 더 명확하게하기 위해 동일한 원본 이미지에서 파생 된 "가족"으로 그룹화 된 다양한 이미지가있는 폴더가 있습니다. 예 :

  • 가족 : 71_157,23_850

  • 이미지 : 71_157,23_850_1.jpg, 71_157,23_850_1.png, 71_157,23_850_3.jpg 등

내가 아는 glob에 의해 반환 된 모든 항목을 처리 할 수 ​​있지만 접근 방식이 조금 원형으로 보입니다.

내 두 번째 방법은 os.scandir로했다 : 그것은 이미지 예를 들어, 특정 "가족"을 위해 작동하지만

x = [f.name for f in os.scandir('images') if f.name.startswith(family in movable)] 

물론 이는 전혀 작동하지 않습니다 51_332,-5_545 가족

x = [f.name for f in os.scandir('images') if f.name.startswith('51_332,-5_545')] 

와 내가 예를 들어 루프에서 결과를 연결할 수 있습니다.

그래서, 내 질문 (들)은 다음과 같습니다

  1. 글로브와 상대 경로를 반환하는 방법이 있나요? 아니면 절대 경로가 붙어 있습니까?
  2. os.scandir으로 필터링 된 파일 목록을 "파이썬"방식으로 가져 오는 방법은 무엇입니까?
+0

파이썬 3의'os.scandir' 부분은 이제 작동합니까? – user1767754

답변

1

이 간단한 기능을 사용합니다.

import os, fnmatch 
def List(Folder, Name): 
    '''Function to get List of Files in a folder with a 
     given filetype or filename''' 
    try: 
     string = '*' + Name + '*' 
     FileList = fnmatch.filter(os.listdir(Folder), string) 
     return FileList 
    except Exception as e: 
     print('Error while listing %s files in %s : %s' % (string, Folder, str(e))) 
     return [] 
관련 문제