반응형
Python 을 이용하여 파일 관리를 할 때 Recursive 하게 탐색하는 방법에 대해 소개한다.
Recursive 하게 파일 탐색을 하기 위해서는 os.walk 와 fnmatch.filter 를 사용한다.
내가 사용하는 코드들은 아래와 같다.
하위의 해당하는 파일들을 다 지고 싶다면 AllFileDelete() 함수를 하위의 모든 관련 파일들을 탐색하고 싶다면 AllFileList() 함수를 사용한다.
코드 아래 부분의 main 을 보면 사용방법을 확인 할 수 있을 것이다. 지우고자 하는 파일이 들어있는 최상위 폴더와 지우고자하는 파일의 확장자들을 죽 나열 하면 된다.
아래 코드에서는 C:\temp 폴더아래 있는 zip 파일과 txt 파일을 다 찾는 예이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fnmatch | |
import os | |
def AllFileList(workingDir, *exts): | |
out = [] | |
for root, dirnames, filenames in os.walk(workingDir): | |
for ext in exts: | |
for filenameFullpath in fnmatch.filter(filenames, ext): | |
fullPath = os.path.join(root, filenameFullpath) | |
folderName = root.split(os.sep).pop() | |
out.append(fullPath) | |
return out | |
def AllFileDelete(workingDir, *exts): | |
for root, dirnames, filenames in os.walk(workingDir): | |
for ext in exts: | |
for filenameFullpath in fnmatch.filter(filenames, ext): | |
fullPath = os.path.join(root, filenameFullpath) | |
folderName = root.split(os.sep).pop() | |
if os.path.isfile(fullPath): | |
os.remove(fullPath) | |
else: # # Show an error ## | |
print("Error: %s file not found" % fullPath) | |
if __name__ == '__main__': | |
Filelist = AllFileList('C:\\temp','*.txt') | |
for n in Filelist: | |
print n | |
반응형
'programming language > Python' 카테고리의 다른 글
Python Cartesian Product (0) | 2014.12.05 |
---|---|
Python Computer Algebra System(CAS) package sympy (0) | 2014.12.03 |
Python Pyzo, IEP (0) | 2014.12.03 |
Python 배열의 인덱스도 보기 enumerate (0) | 2014.11.30 |
Python dictionary 안의 dictionary 데이터 타입 (0) | 2014.11.16 |
Eclipse Python Plugin Pydev 설치 (0) | 2014.11.15 |
Python에서 Clipboard 사용하기 pyperclip (0) | 2014.04.22 |
Python BeautifulSoup 를 사용한 로또 번호 불러오기 (2) | 2014.04.21 |
댓글