2013-07-22 3 views
1

주어진 폴더 내에서 모든 파일 (선택적으로 하위 폴더 (선택적으로 하위 디렉토리로 재귀적임))을 열거하는 일반적인 방법이 있습니까? 그래서 나는 폴더 경로를 전달하고 결과 전체 경로 목록을 얻는다.Python - 폴더에서 모든 파일 목록 가져 오기 (더 많은 옵션 포함)

이 결과에서 모든 읽기 전용 파일과 숨겨진 파일을 모두 제외하는 방법을 보여 주면 더 좋을 것입니다. 그래서 입력 PARAMS :

  • 디렉토리 : 폴더의 전체 경로
  • option_dirs는 :
  • option_subdirs 목록에 DIRS 경로를 포함 과정을 또한 디렉토리
  • option_no_ro의 모든 하위 디렉토리 : 제외 읽기 전용
  • 을 파일
  • option_no_hid : 숨김 파일 제외

Python2.

+3

가능한 중복 (http://stackoverflow.com/questions/3207219/how- [파이썬의 디렉토리의 모든 파일을 나열하는 방법] to-list-all-of-a-python 디렉토리) – ecatmur

+0

링크는 1) 및 2) 옵션에 대한 답변을 보여줍니다. 하지만 RO 및 숨겨진 파일을 제외하는 방법은 무엇입니까? – Prog1020

답변

5

아마도 과 os.access을 조사해야합니다. 당신이 뭔가를 할 수있는 실제 구현을 위해

:

import os 

def get_files(path, option_dirs, option_subdirs, option_no_ro, option_no_hid): 
    outfiles = [] 
    for root, dirs, files in os.walk(path): 
     if option_no_hid: 
      # In linux, hidden files start with . 
      files = [ f for f in files if not f.startswith('.') ] 
     if option_no_ro: 
      # Use os.path.access to check if the file is readable 
      # We have to use os.path.join(root, f) to get the full path 
      files = [ f for f in files if os.access(os.path.join(root, f), os.R_OK) ] 
     if option_dirs: 
      # Use os.path.join again 
      outfiles.extend([ os.path.join(root, f) for f in files ]) 
     else: 
      outfiles.extend(files) 
     if not option_subdirs: 
      # If we don't want to get subdirs, then we just exit the first 
      # time through the for loop 
      return outfiles 
    return outfiles 
+0

'import os.path'; 'option_no_ro'가 사용되지 않습니다. Tks. – Prog1020

+0

어쩔 수 없으므로'option_no_ro'가 사용되었습니다. – mr2ert

관련 문제