간만에 python 을 사용하는데 directory 를 traverse 하는데 os.walk 를 사용하면 좋다고 해서 사용했는데, 처음에 잘 이해가 안됐지만, 알고나니 사용하기 편해서 대충 적어놓는다.
api 문서
api 문서 : https://docs.python.org/2/library/os.html사용법 예제
def recursiveWalk(root):
for curDirname, dirnames, filenames in os.walk(root, topdown=True):
depth = curDirname.count(os.path.sep) - root.count(os.path.sep)
# traverse all the files in the current directory
for filename in filenames:
# do something for files
print filename
path --- file01.txt
|
+- tt.txt
|
+- walkandparseurl.py
|
+- 01 ---- file01-01-1.txt
| |
| +-- file01-01-2.txt
|
|
+- 02 ---- file01-02-1.txt
만약 위의 같은 directory 구조가 있을 때 walkandparseurl.py 의 main 에서 recursiveWalk(os.getcwd()) 를 실행한다면 결과는 아래와 같이 나온다.
topdown = True 일 때
file01.txt tt.txt walkandparseurl.py file01-01-1.txt file01-01-2.txt file01-02-1.txt
topdown = False 일 때
file01-01-1.txt file01-01-2.txt file01-02-1.txt file01.txt tt.txt walkandparseurl.py
댓글 없음:
댓글 쓰기