2011-09-27 2 views
1

다음 예제에서는 디렉토리를 "둘러보고"모든 파일의 이름을 인쇄하고 모든 디렉토리에서 반복적으로 호출합니다.파일 이름 및 경로 문제가 발생했습니다.

import os 
def walk(dir): 
    for name in os.listdir(dir): 
     path = os.path.join(dir,name) 
     if os.path.isfile(path): 
      print path 
     else: 
      walk1(path) 

os.path.join` takes a directory and a file name and joins them into a complete path. 

내 운동 : 도보 그래서 대신 파일의 이름을 인쇄 수정, 그것은 이름의 목록을 반환합니다.

누군가이 기능이 한 줄에 무엇을하는지 설명 할 수 있습니까? 나는 좋은 생각을 가지고있다. 그러나 그것이 줄에 도착할 때 : else: walk(path), 그게 무슨 일을하는지 아무런 설명이 없기 때문에 나를 버린다.

def walk1(dir): 
    res = [] 
    for name in os.listdir(dir): 
     path = os.path.join(dir,name) 
     if os.path.isfile(path): 
      res.append(path) 
     else: 
      walk1(path) 
    return res 

내 출력이 단지 단순한 몇 많은 출력 선에서 갔다 :이 연습, 나는 목록으로 변경하기 위해 생각할 수있는 유일한 방법입니다. 이 작업이 올바르게 수행 되었습니까?

답변

1

다음은 재귀에 대한 작은 수정 사항이있는 주석이 달린 버전입니다.

def walk1(dir): 
    res = [] 
    # for all entries in the folder, 
    for name in os.listdir(dir): 
     # compute the path relative to `dir` 
     path = os.path.join(dir,name) 
     # include entries recursively. 
     if os.path.isfile(path): 
      # the path points to a file, save it. 
      res.append(path) 
     else: 
      # the path points to a directory, so we need 
      # to fetch the list of entries in there too. 
      res.extend(walk1(path)) 
    # produce all entries at once. 
    return res 
+0

또한 다음 연습에서는 _os_ _ _ 내 함수를 talk_walk_라고합니다. 그러나이 문서를 읽으려면; 주어진 디렉토리와 하위 디렉토리에있는 파일의 이름을 출력해야합니다. 그걸 정확하게 해석한다면 res.extend가되는 것도 아닌가? –

1

이미 가지고있는 재귀 결과를 추가해야합니다.

+0

방금 ​​깨달았습니다. walk (path)는 내가 정의한 함수와 동일한 재귀가 아닙니다.><죄송합니다 ... walk1() –

1

내가 쓴 작은 모듈, pathfinder은 쉽게 (내 의견으로는 어쨌든에서) 경로를 찾을 수 있습니다.

from pathfinder import pathfind 
paths = pathfind(a_dir, just_files=True) 

이것은 단지 os.walk의 맨 위에있는 계층이지만 주변의 혼란을 제거합니다.

관련 문제