2017-12-17 16 views
0

나는 디렉토리를 통해 이동하고 일반적인 Windows 설치 프로그램 확장명을 가진 파일을 찾아 삭제하는 스크립트를 작성하고 있습니다. 내가 목록을 가지고 이것을 실행할 때 (.msi 또는 .exe를 검사하는 것보다), 중첩 된 루프를 다시 통과 할 때 브레이크가 걸린다. 그것은 마치 내 목록을 실행하는 것처럼 보이지만 한 유형의 확장을 삭제 한 다음 루프를 다시 실행하고 동일한 확장명을 찾기 위해 attemtps가 예외를 throw합니다.os walk 동안 이미 삭제 된 파일에 대한 루프 스레딩 예외에 대해

Found directory: . 
Found directory: .\test_files 
     Deleting test.cub 
Traceback (most recent call last): 
    File "test.py", line 13, in <module> 
    os.remove(fileName) 
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.cub' 

나는 OS 거리에 읽어 : 나는 os.remove 그것을 실행하려고하면

> C:\Users\User\Documents\Python Scripts>python test.py < test_run.txt 
> Found directory: . Found directory: .\test_files 
>   Deleting test.cub 
>   Deleting test.idt 
>   Deleting test.idt 
>   Deleting test.msi 
>   Deleting test.msm 
>   Deleting test.msp 
>   Deleting test.mst 
>   Deleting test.pcp 
>   Deleting test1.exe 

는 다음과 제공 : 저는 여기에 단순히 파일을 제거 인쇄 할 수 있지만 출력은 제대로 작동하는 것 같아서이 스크립트가 잘못되어있는 부분을 파악할 수 없습니다. 코드는 다음과 같습니다 : 파일 test.cub

import os 

myList = [".msi", ".msm", ".msp", ".mst", ".idt", ".idt", ".cub", ".pcp", ".exe"] 


rootDir = '.' 
for dirName, subdrList, fileList in os.walk(rootDir): 
    print('Found directory: %s' %dirName) 
    for fileName in fileList: 
     for extName in myList: 
      if(fileName.endswith(extName)): 
        print('\t Deleting %s' % fileName) 
        os.remove(fileName) 

답변

1

올바른 상대 이름은 .\test_files\test.cub입니다.

제공하는 상대 이름은 .\test.cub입니다.

IT는 os.walk documentation에서 말하기를 :

os.path.join(dirpath, name)를 수행 dirpath에서 파일이나 디렉토리 (상단로 시작) 전체 경로를 얻을 수 있습니다.

+0

그래, 그게 ... 그리고 중첩 루프에서 휴식이 필요했습니다. – Psyllex