2016-07-16 4 views
0

그래서 비어 있지 않은 디렉토리를 청소해야합니다. 난 내가 rmtree 및 RMDIR를 사용하려고 JDK가 설치파이썬에서 비어 있지 않은 디렉토리를 삭제하십시오.

def clean_dir(location): 
    fileList = os.listdir(location) 

    for fileName in fileList: 
     fullpath=os.path.join(location, fileName) 
     if os.path.isfile(fullpath): 
      os.chmod(fullpath, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
      os.remove(location + "/" + fileName) 
     elif os.path.isdir(fullpath): 
      if len(os.listdir(fullpath)) > 0: 
       clean_dir(fullpath) 
      #os.rmdir(location + "/" + fileName) 
      shutil.rmtree(location + "/" + fileName) 

    return 

을 제거하려고 다음 function.For 테스트 이유를 만들었습니다,하지만 실패합니다. 내가 rmtree를 사용하여있어

오류 :

OSError: Cannot call rmtree on a symbolic link

을 그리고 이것은 내가 rmdir을 사용할 때 내가 가진 오류입니다 :

OSError: [Errno 66] Directory not empty: '/tmp/jdk1.8.0_25/jre/lib/amd64/server'

코드는 창에 올바르게 작동합니다. 하지만 어떤 이유로 리눅스에서 실패합니다.

+0

에 대한 새로운 ELIF를 추가하고 링크 해제 옵션을 추가했다. https://en.wikipedia.org/wiki/Symbolic_link – iScrE4m

+0

심볼릭 링크라면'os.unlink (...)'만 있으면 충분하다고 생각합니다. (명확히하기 위해 심볼릭 링크를 지울 뿐이며 심볼릭 링크가 가리키는 것은 삭제하지 않습니다.) – smarx

+0

IIRC,'os.unlink'도 파일을 삭제해야합니다. – kronenpj

답변

1

kronenpj 감사합니다. 하지만 심볼릭 링크가 있으면 삭제하려고 시도하는 것이 정상적인 파일이므로 실패합니다. 나는 당신이 심볼릭 링크가 아닌 디렉토리에 rmtree을 가리키는 심볼릭 링크

 
def clean_dir(location): 
    fileList = os.listdir(location)

for fileName in fileList: fullpath=os.path.join(location, fileName) if os.path.isfile(fullpath): os.chmod(fullpath, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) os.remove(os.path.join(location, fileName)) elif os.path.islink(fullpath): os.unlink(fullpath) elif os.path.isdir(fullpath): if len(os.listdir(fullpath)) > 0: clean_dir(fullpath) #os.rmdir(location + "/" + fileName) shutil.rmtree(os.path.join(location, fileName)) return

+0

절대적으로 옳다. 나는'remove()'가 심볼릭 링크를 제대로 처리 할 것인지 아닌지에 대해 확신하지 못했다. – kronenpj

2

Windows와 Linux의 차이점 중 하나 (UNIX는 실제로)가 파일 시스템을 처리합니다. 난 당신의 코드에 의지 적어도 도움을 추가하는 경우 추가 믿고 :

... 
for fileName in fileList: 
    fullpath = os.path.join(location, fileName) 
    ## |<-- Handle symlink -->| 
    if os.path.islink(fullpath) or os.path.isfile(fullpath): 
     os.chmod(fullpath, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
     os.remove(os.path.join(location, fileName)) 
    elif os.path.isdir(fullpath): 
     if len(os.listdir(fullpath)) > 0: 
      clean_dir(fullpath) 
     #os.rmdir(os.path.join(location, fileName)) 
     shutil.rmtree(os.path.join(location, fileName)) 
... 

이 제대로 항목이 심볼릭 링크 인 경우를 처리하고 단지 파일처럼 제거해야합니다. 나는 chmod이 필요한지 확신하지 못합니다 - 아마도 링크 대상에서 작동하지만 파일과 같은 방식으로 처리해서는 안됩니다.

그러나 상징 링크에 대한 os.path.file은 "물건"이 가리키는 유형을 반환하므로 링크 자체와 지적 된 것의 구분을 위해 추가 확인이 필요합니다. 또한 휴대하기 위해 "/"를 덧붙이 지 않고 새로 편집 한대로 os.path.join을 사용하십시오.