2009-07-07 2 views

답변

12

glob 모듈을 사용하십시오.

>>> import glob 
>>> glob.glob('./[0-9].*') 
['./1.gif', './2.txt'] 
>>> glob.glob('*.gif') 
['1.gif', 'card.gif'] 
>>> glob.glob('?.gif') 
['1.gif'] 
+0

매력처럼 작동했습니다.이 빠른 답변에 감사드립니다. – JustRegisterMe

2

글로브의 대답은하지만 완성도를 위해서, 쉽게 : 당신은 또한 os.listdir과 정규 표현식 검사를 사용할 수 있습니다

import os 
import re 
dirEntries = os.listdir(path/to/dir) 
for entry in dirEntries: 
    if re.match(".*tmp.*\.log", entry): 
    print entry 
+0

다시 사용할 필요가 없습니다. – ghostdog74

+0

좋습니다. *보다 복잡한 검색이 필요합니다. – JustRegisterMe

0
코드는 아래를 보여 이전의 대답에 확장

더 복잡한 검색 케이스.

구성 파일에 의해 크게 제어되는 응용 프로그램이 있습니다. 사실 서로 다른 장단점을 가진 여러 버전의 구성이있었습니다. 그래서 하나의 설정은 철저한 작업을하게되지만 매우 느려지지만 다른 설정은 훨씬 빠르지 만 철저히하지는 않을 것입니다. 그래서 GUI는 다른 설정에 해당하는 옵션으로 구성 콤보 박스를 갖게됩니다. 시간이 지남에 따라 구성 집합이 커질 것이라고 생각했기 때문에 응용 프로그램에서 파일 목록과 해당 옵션 (및 해당 순서)을 하드 코딩하지 않고이 모든 것을 전달하는 파일 명명 규칙을 사용했습니다 정보.

내가 사용한 명명 규칙은 다음과 같습니다. 파일은 $ MY_APP_HOME/dat 디렉토리에 있습니다. 파일 이름은 my_config_와 콤보 색인 번호, 콤보 항목의 텍스트 순으로 시작됩니다. 예를 들어, 디렉토리에 my_config_11_fast_but_sloppy.txt, my_config_100_balanced.txt, my_config_3_thorough_but_slow.txt 파일이 들어 있으면 내 콤보 상자에 옵션이 순서대로 제공됩니다 (철저히하지만 천천히, 빠르지 만 조롱하고 균형 잡힘).

그래서 런타임에 나는 디렉토리

  • 에 따라 콤보 상자에 넣어
  • 정렬 옵션을 모든 파일 이름에서 옵션 목록을 추출 내 설정 파일을 찾기

    1. 에 필요 인덱스

    MyConfiguration 클래스는 아래에 알을 수행하는 선택 옵션에서 파일 경로를 얻을 수있을 리터는 목적 :-)을 설명하는 저를 데리고가 다음과 같이 사용될 수 있음을 유의하게 적은 코드 (단 몇 줄의 작업 :

    import os, re 
    
    class MyConfiguration: 
        def __init__(self): 
         # determine directory that contains configuration files 
         self.__config_dir = ''; 
         env_name = 'MY_APP_HOME' 
         if env_name in os.environ: 
          self.__config_dir = os.environ[env_name] + '/dat/'; 
         else: 
          raise Exception(env_name + ' environment variable is not set.') 
         # prepare regular expression 
         regex = re.compile("^(?P<file_name>my_config_(?P<index>\d+?)_(?P<desc>.*?)[.]txt?)$",re.MULTILINE) 
         # get the list of all files in the directory 
         file_names = os.listdir(self.__config_dir) 
         # find all files that are our parameters files and parse them into a list of tuples: (file name, index, item_text) 
         self.__items = regex.findall("\n".join(file_names)) 
         # sort by index as an integer 
         self.__items.sort(key=lambda x: int(x[1])) 
    
        def get_items(self): 
         items = [] 
         for item in self.__items: 
          items.append(self.__format_item_text(item[2])) 
         return items 
    
        def get_file_path_by_index(self, index): 
         return self.__config_dir + self.__items[index][0] 
    
        def __format_item_text(self, text): 
         return text.replace("_", " ").title(); 
    
    : 여기
    # populate my_config combobox 
    self.my_config = MyConfiguration() 
    self.gui.my_config.addItems(self.my_config.get_items()) 
    
    # get selected file path 
    index = self.gui.my_config.currentIndex() 
    self.config_file = self.my_config.get_file_path_by_index(index); 
    

    는 MyConfiguration 클래스입니다