-
[ Python ] shutil모듈의 rmtree 메소드를 이용한 하위 디렉토리와 파일 삭제Python/Python Programming 2018. 5. 22. 21:54
shutil.rmtree로 삭제된 파일은 복구 할 수 없으므로, 유의하여 진행한다. 실무에서 사용할 경우 본인환경에서 충분한 테스트를 수행해야 한다.
shutil.rmtree('경로')와 같이 이용할 수 있으나 한번 삭제되면 복구될 수 없으니 고민하여 수행하는 것이 좋다.
1. 삭제될 경로확인
2. 해당 명령어가 실행될 경우 삭제되는 폴더와 파일
3. 실행 전 Y / N 트리거
파일삭제 전 os.path.walk를 이용해 삭제리스트를 출력한다. 폴더와 파일수가 많으면 os.listdir을 이용해 1depth만 출력할 수 있다.
경로는 os.abspath를 이용해 상대경로가 입력되더라도 절대경로가 출력된다. 파일작업시 '절대경로'와 '상대경로'의 결과값이 달라질 있으니 중요하고, 또 중요하다.import shutil import os def func1(dir): try: if os.listdir(dir): for (path, dir, files) in os.walk(os.path.abspath(dir)): print(path, files, sep='\t') excute() except Exception as e: return e def excute(): print('*'*100) print('* 삭제되는 디렉토리와 파일 리스트 입니다. 절대경로로 표기합니다.') print('* 경고! rmtree 메소드는 하위 디렉토리 및 모든파일들을 삭제합니다.') print('* 휴지통으로 복구할 수 없습니다. 필요시 반드시 백업하시기 바랍니다.') deleteKey = input('%s 해당폴더를 삭제하시겠습니까 [Y/N]' %os.path.abspath(dir)) if deleteKey == 'y': try: shutil.rmtree(dir) except Exception as e: print(e) else: print('중단되었습니다.') dir = 'D:\Backup' print(func1(dir)) D:\Backup ['test1.txt', 'test2.txt', 'test3.txt'] **************************************************************************************************** * 삭제되는 디렉토리와 파일 리스트 입니다. 절대경로로 표기합니다. * 경고! rmtree 메소드는 하위 디렉토리 및 모든파일들을 삭제합니다. * 휴지통으로 복구할 수 없습니다. 필요시 반드시 백업하시기 바랍니다. D:\Backup 해당폴더를 삭제하시겠습니까 [Y/N]y
'Python > Python Programming' 카테고리의 다른 글
[Python] ODBC driver를 이용한 mssql 연결 (0) 2018.12.29 [Python] File Copy (파일복사) (0) 2018.09.03 [Python] FTP TLS Download 다운로드 (0) 2018.08.07 [Python] Comparison of Datetime Type Using Python (0) 2018.06.15 [Python] 3.6+에서 사전자료형(Dict)은 입력순서를 보존 (0) 2018.05.19 [Python] strip, rstrip, lstrip - 공백과 문자 제거 함수 (0) 2018.05.19 [Python] Gmail 보내기 (0) 2018.05.18 [Python] 단축평가(short-circuit evalution) (0) 2018.05.15