폴더에 파일을 삭제하는 방법 또는 파이썬?
['오스콜리모프 ()'] [1] 절감뿐만 파일입니다.
['세자르 디르 ()'] [2] 절감뿐만 빈 디렉터리입니다.
['슈틸스마트리 ()'] [3] deletes 디렉터리입니다 및 그 내용이.
['길'] [4] 의 객체를 파이썬 3.4+ ['파트리브'] (https://docs.python.org/3/library/pathlib.html) 도 이러한 인스턴스입니다 모듈에서는 노출시키는 방법:
['파트리브룩스파스트런링크 ()'] [5] 절감뿐만 파일 또는 심볼릭 링크.
['파트리브룩스파스콜름디르 ()'] [6] 절감뿐만 빈 디렉터리입니다.
[1]: http://docs.python.org/library/os.html # 오스콜리모프 [2]: http://docs.python.org/library/os.html # 세자르 디르 [3]: http://docs.python.org/library/shutil.html # 슈틸스마트리 [4]: https://docs.python.org/3/library/pathlib.html # 파트리브룩스파스 [5]: https://docs.python.org/3/library/pathlib.html # 파트리브룩스파스트런링크 [6]: https://docs.python.org/3/library/pathlib.html # 파트리브룩스파스콜름디르
import os
os.remove("/tmp/<file_name>.txt")
또는
import os
os.unlink("/tmp/<file_name>.txt")
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
< pre>; 파일 이름 입력 삭제할 수 있습니다. demo.t스트 오류: no such file or demo.t스트 디렉터리입니다.
파일 이름 입력 삭제할 수 있습니다. 라르스테스트 오류: 작업 라르스테스트 수 없습니다.
파일 이름 입력 삭제할 수 있습니다. 프로스테스트 < /pre>;
shutil.rmtree()
'예' 슈틸스마트리 ()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
사용
shutil.rmtree(path[, ignore_errors[, onerror]])
(Http://otl. 관한 문서가 완료하십시오 슈틸) 및/또는
os.remove
및
os.rmdir
(관한 문서가 완료하십시오 [os] [2]).
[2]: http://docs.python.org/library/os.html # 오스콜리모프
생성 함수 당신꺼에요 보세요들.
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
['파트리브'] [0] 모듈에서는 내장현 사용할 수 있습니다 (单捞磐啊 파이썬 3.4+ 수축됐는데 박포르츠, 기존 버전에 대해 켜짐이 피피: '파트리브', 'pathlib2').
[3] 은 ['연결해제'] 그 파일을 제거하는 방법:
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
[0]: https://docs.python.org/library/pathlib.html # 모듈에서는 파트리브
[3]: https://docs.python.org/library/pathlib.html # 파트리브룩스파스트런링크 [4]: https://docs.python.org/library/pathlib.html # 파트리브룩스파스콜름디르
파이썬 3, 지루려면 위한 파일 및 디렉터리 개별적으로 list. ['연결해제'] [1] 및 ['rmdir'] [2] '길' 객체에는 각각 방법:
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
상대 경로를 통한 오브젝트에도 사용할 수도 있습니다 '길' '와' 파트리시우드 현재 작업 디렉토리에 확인할 수 있습니다.
그래서 레이블된 아래에 있는 개별 파일 및 디렉터리 제거하기 위한 파이썬 2 절을 참조하십시오.
디렉터리입니다 사용하여 지루려면 내용이 있는 ['슈틸스마트리'] [3] 에서 사용할 수 있으며, 이것이 파이썬 2 와 3:
from shutil import rmtree
rmtree(dir_path)
파이썬 3.4 '의 새로운 길' 은 객체.
from pathlib import Path
# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()
file_path = directory_path / 'file'
file_path.touch()
그리고 지금.
>>> file_path.is_file()
True
이제 let& # 39 의 삭제하십시오. 첫 파일:
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
여러 개의 파일을 사용할 수 있습니다 - # 39 의 첫 글 로빙 지루려면 let& 엔드입니다 몇 개의 파일을 만듭니다.
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
그럼 그냥 반복할 이 글롭 패턴:
>>> for each_file_path in directory_path.glob('*.my'):
... print(f'removing {each_file_path}')
... each_file_path.unlink()
...
removing ~/directory/foo.my
removing ~/directory/bar.my
이제 각각 분리, 디렉터리입니다.
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
우리가 원하는 디렉터리입니다 와일드링이 지루려면 and everything in it? 이를 위해 ',' 슈틸스마트리 사용 용도
file_path.parent.mkdir()
file_path.touch()
참고로 '및' s # 39, 빈, 그래서 마트리 않으면 실패할 rmdir it& 너무나 편리한:
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/excelsiora/directory'
이제 마트리 임포트합니다 대한 심사와 디렉토리에는 하여 장소:
from shutil import rmtree
rmtree(directory_path) # remove everything
우리는 전부 분리되었는지 볼 수 있다.
>>> directory_path.exists()
False
$ pip install pathlib2
'다음' 에 대한 라이브러리 앨리어스가 파트리브 수 있습니다.
import pathlib2 as pathlib
직접 스피커에만 임포트하십시오 '길' 객체에는 것처럼 여기).
from pathlib2 import Path
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
또는
unlink(join(expanduser('~'), 'directory/file'))
['세자르 디르'] [6] 와 함께 디렉터리용 제거할 수 있습니다.
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
단, 또한 뿐이다 - ['오스콜리모프레디스'] [7] 빈 디렉터리를 절감뿐만 재귀적으로 있지만 맞게 활용.
[1]: https://docs.python.org/3/library/pathlib.html # 파트리브룩스파스트런링크 [2]: https://docs.python.org/3/library/pathlib.html # 파트리브룩스파스콜름디르 [3]: https://docs.python.org/3/library/shutil.html # 슈틸스마트리
[5]: https://docs.python.org/2/library/os.html # 오스콜리모프 [6]: https://docs.python.org/2/library/os.html # 세자르 디르 [7]: https://docs.python.org/2/library/os.html # 오스콜리모프레디스
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
os.unlink(path, *, dir_fd=None)
또는
os.remove(path, *, dir_fd=None)
두 가지 기능을 모두 동일한 의미 있다. 이 기능을 제거 (삭제) 파일 경로를. 이 경우 경로 파일이므로 디렉터리입니다 관심용 예외는 아닐 수 없다.
shutil.rmtree(path, ignore_errors=False, onerror=None)
또는
os.rmdir(path, *, dir_fd=None)
전체 디렉터리 트리 () ',' 슈틸스마트리 제거하기 위해 사용할 수 있습니다. '때' 비어 있고 디렉토리에는 세자르 디르 때만 존재합니다.
os.removedirs(name)
이 모든 제거하시겠습니까 빈 상위 디렉터리입니다 자체 보살피되 모피쳐 디스크입니다. diskid 일부 내용을
>, ex. 오스콜리모프레디스 (& # 39, abc/xyz/pqr& # 39;) & # 39, & # 39 는 명령에 따라 디렉터리용 분리하십시오 abc/xyz/pqr& abc/xyz& # 39, # 39;;; # 39, & # 39 와 abc&. 만약 그들이 비어 있다.
자세한 정보는 공식 확인 설명서: ['오스트런링크'] (https://docs.python.org/library/os.html # 오스트런링크), ['오스콜리모프'] (https://docs.python.org/library/os.html # 오스콜리모프), ['세자르 디르'] (https://docs.python.org/library/os.html # 세자르 디르), ['슈틸스마트리'] (https://docs.python.org/library/shutil.html # 슈틸스마트리), ['오스콜리모프레디스'] (https://docs.python.org/3/library/os.html # 오스콜리모프레디스)
"만약 내가 '는 자신의 코드를 사용하여 하위 추천합니까 아름다운 읽기와 쓰기 cup of tea.
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
및 소프트웨어 엔지니어가 아닌 경우, 아마도 주피터 사용하는 것이 좋습니다. 배시 (bash 명령의세 입력하십시ᄃ오 됩니다.
!rm -r my_dir
전통적으로 사용하는 슈틸 ',':
import shutil
shutil.rmtree(my_dir)