반응형
Python에서 rm -rf를 사용하는 가장 쉬운 방법
rm -rf
Python 에서 해당 작업을 수행하는 가장 쉬운 방법은 무엇입니까 ?
import shutil
shutil.rmtree("dir-you-want-to-remove")
유용하지만 rmtree는 동일 rm -f
하지 않습니다 . 단일 파일을 제거하려고하면 오류가 발생 하지만 그렇지 않습니다 (아래 예제 참조).
이 문제를 해결하려면 경로가 파일인지 디렉토리인지 확인하고 그에 따라 조치를 취해야합니다. 다음과 같은 것이 트릭을 수행해야합니다.
import os
import shutil
def rm_r(path):
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.remove(path)
참고 :이 함수는 문자 또는 블록 장치를 처리하지 않습니다 ( stat
모듈 사용이 필요함 ).
rm -f
와 Python의 차이 예shutils.rmtree
$ mkdir rmtest
$ cd rmtest/
$ echo "stuff" > myfile
$ ls
myfile
$ rm -rf myfile
$ ls
$ echo "stuff" > myfile
$ ls
myfile
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.rmtree('myfile')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/shutil.py", line 236, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/usr/lib/python2.7/shutil.py", line 234, in rmtree
names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'myfile'
편집 : 심볼릭 링크 처리; @pevik의 의견에 따른 제한 사항에 유의하십시오.
import os
import shutil
def rm_r(path):
if not os.path.exists(path):
return
if os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path)
Gabriel Grant의 버전을 약간 개선했습니다. 이것은 디렉토리에 대한 심볼릭 링크에서도 작동합니다. 참고 : 함수는 Un * x 문자 및 블록 장치를 처리 하지 않습니다 ( stat 모듈 을 사용해야 함 ).
파일 삭제를 차단하는 Windows의 해결 방법은 파일을 자르는 것입니다.
outputFile = open(r"filename.txt","w")
outputFile.truncate()
outputFile.close()
outputFile = open(r"filename.txt","a+")
출처 : https://stackoverflow.com/a/2769090/6345724
shutil.rmtree ()가 정답이지만 다른 유용한 함수 인 os.walk ()를 살펴보십시오.
def delite(filepath):
import os, stat, sys
def intertwin(_list):
list1 = []
for i in _list:
list1 += i
return list1
allpath = os.walk(filepath)
walk = []
dirs = []
path = []
allfiles = []
for i in allpath:
walk.append(i)
for i in walk:
dirs.append(i[0])
for _dir in dirs:
os.chdir(_dir)
files = os.listdir(_dir)
files1 = []
for i in files:
files1.append(_dir + '\\' + i)
files = files1[:]
allfiles.append(files)
allfiles = intertwin(allfiles)
for i in allfiles:
os.chmod(i, stat.S_IRWXU)
allfiles.reverse()
os.chdir(sys.path[0])
for i in allfiles:
try:
os.remove(i)
except:
try:
os.rmdir(i)
except:
pass
os.chmod(filepath, stat.S_IRWXU)
try:
os.remove(filepath)
except:
os.rmdir(filepath)
allfiles.reverse()
os.chdir(sys.path[0])
for i in allfiles:
try:
os.remove(i)
except:
try:
os.rmdir(i)
except:
pass
os.chmod(filepath, stat.S_IRWXU)
try:
os.remove(filepath)
except:
os.rmdir(filepath)
다음과 같이하십시오.
import os
dirname = "path_to_directory_to_remove"
os.system("rm -rf %s" % dirname)
참고 URL : https://stackoverflow.com/questions/814167/easiest-way-to-rm-rf-in-python
반응형
'IT TIP' 카테고리의 다른 글
플로트에 가능한 가장 작은 플로트 추가 (0) | 2020.12.06 |
---|---|
WPF 응용 프로그램을 전체 화면으로 만들기 (표지 시작 메뉴) (0) | 2020.12.06 |
`[super viewDidLoad]`규칙 (0) | 2020.12.04 |
SQL 주석 헤더 예 (0) | 2020.12.04 |
TypeCasting의 성능 (0) | 2020.12.04 |