etc./StackOverFlow

Python에서 파일 또는 폴더를 삭제하는 방법은 무엇입니까?

청렴결백한 만능 재주꾼 2021. 11. 9. 00:28
반응형

질문자 :Zygimantas


Python에서 파일이나 폴더를 어떻게 삭제합니까?




Python 3.4+ pathlib Path 개체는 다음 인스턴스 메서드도 노출합니다.


RichieHindle

파일을 삭제하는 Python 구문

 import os os.remove("/tmp/<file_name>.txt")

또는

 import os os.unlink("/tmp/<file_name>.txt")

또는

Python 버전용 pathlib 라이브러리 >= 3.4

 file_to_rem = pathlib.Path("/tmp/<file_name>.txt") file_to_rem.unlink()

Path.unlink(missing_ok=False)

파일 또는 심볼릭 링크를 제거하는 데 사용되는 링크 해제 방법입니다.

missing_ok가 false(기본값)인 경우 경로가 존재하지 않으면 FileNotFoundError가 발생합니다.
missing_ok가 true이면 FileNotFoundError 예외가 무시됩니다(POSIX rm -f 명령과 동일한 동작).
버전 3.8에서 변경: missing_ok 매개변수가 추가되었습니다.

모범 사례

  1. 먼저 파일이나 폴더가 있는지 확인하고 해당 파일만 삭제합니다. 이는 두 가지 방법으로 달성할 수 있습니다.
    NS. os.path.isfile("/path/to/file")
    NS. exception handling. 사용합니다.

os.path.isfile

 #!/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))

각 출력

삭제할 파일명 입력 : demo.txt
오류: demo.txt - 해당 파일이나 디렉토리가 없습니다.

삭제할 파일명 입력 : rrr.txt
오류: rrr.txt - 작업이 허용되지 않습니다.

삭제할 파일명 입력 : foo.txt

폴더를 삭제하는 Python 구문

 shutil.rmtree()

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))

Anand Tripathi

사용하다

 shutil.rmtree(path[, ignore_errors[, onerror]])

(shutil 에 대한 전체 문서 참조) 및/또는

 os.remove

그리고

 os.rmdir

( os 에 대한 완전한 문서)


Mihai Maruseac

os.removeshutil.rmtree 모두 사용하는 강력한 기능입니다.

 def remove(path): """ param <path> could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(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))

flycee

내장된 pathlib 모듈을 사용할 수 있습니다 pathlib 필요하지만 PyPI에 이전 버전에 대한 백포트가 있습니다: pathlib , pathlib2 ).

파일을 제거하려면 unlink 방법이 있습니다.

 import pathlib path = pathlib.Path(name_of_file) path.unlink()

또는 폴더를 제거하는 rmdir

 import pathlib path = pathlib.Path(name_of_folder) path.rmdir()

MSeifert

Python에서 파일이나 폴더를 어떻게 삭제합니까?

Python 3의 경우 파일과 디렉터리를 개별적으로 제거하려면unlinkrmdir Path 개체 메서드를 각각 사용합니다.

 from pathlib import Path dir_path = Path.home() / 'directory' file_path = dir_path / 'file' file_path.unlink() # remove file dir_path.rmdir() # remove directory

Path 개체와 함께 상대 경로를 사용할 수도 Path.cwd 사용하여 현재 작업 디렉터리를 확인할 수 있습니다.

Python 2에서 개별 파일 및 디렉터리를 제거하려면 아래에 레이블이 지정된 섹션을 참조하세요.

내용이 있는 디렉토리를 제거하려면 shutil.rmtree 사용하고 Python 2 및 3에서 사용할 수 있습니다.

 from shutil import rmtree rmtree(dir_path)

데모

Python 3.4의 새로운 기능은 Path 객체입니다.

하나를 사용하여 사용법을 보여주기 위해 디렉토리와 파일을 생성해 보겠습니다. / 를 사용한다는 점에 유의하십시오. 이는 운영 체제 간의 문제와 Windows에서 백슬래시 사용으로 인한 문제를 해결합니다( \\ r"foo\bar" 과 같은 원시 문자열을 사용해야 하는 경우) r"foo\bar" ):

 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

이제 삭제해 보겠습니다. 먼저 파일:

 >>> file_path.unlink() # remove file >>> file_path.is_file() False >>> file_path.exists() False

globbing을 사용하여 여러 파일을 제거할 수 있습니다. 먼저 이를 위해 몇 개의 파일을 생성해 보겠습니다.

 >>> (directory_path / 'foo.my').touch() >>> (directory_path / 'bar.my').touch()

그런 다음 glob 패턴을 반복합니다.

 >>> 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

디렉토리와 그 안의 모든 것을 제거하려면 어떻게 해야 할까요? 이 사용 사례의 경우 shutil.rmtree

디렉터리와 파일을 다시 생성해 보겠습니다.

 file_path.parent.mkdir() file_path.touch()

rmdir 이 비어 있지 않으면 실패하므로 rmtree가 매우 편리합니다.

 >>> 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/username/directory'

이제 rmtree를 가져오고 디렉터리를 함수에 전달합니다.

 from shutil import rmtree rmtree(directory_path) # remove everything

전체가 제거된 것을 볼 수 있습니다.

 >>> directory_path.exists() False

파이썬 2

Python 2를 사용하는 경우 pip로 설치할 수 있는 pathlib2 라는 pathlib 모듈의 백포트가 있습니다.

 $ pip install pathlib2

그런 다음 라이브러리의 별칭을 pathlib

 import pathlib2 as pathlib

Path 개체를 직접 가져옵니다(여기에 설명된 대로).

 from pathlib2 import Path

os.remove 또는 os.unlink 하여 파일을 제거할 수 있습니다.

 from os import unlink, remove from os.path import join, expanduser remove(join(expanduser('~'), 'directory/file'))

또는

 unlink(join(expanduser('~'), 'directory/file'))

os.rmdir 하여 디렉토리를 제거할 수 있습니다.

 from os import rmdir rmdir(join(expanduser('~'), 'directory'))

os.removedirs 도 있습니다. 이는 빈 디렉토리만 재귀적으로 제거하지만 사용 사례에 적합할 수 있습니다.


Aaron Hall

shutil.rmtree는 비동기 함수이므로 완료 시점을 확인하려면 while...loop를 사용할 수 있습니다.

 import os import shutil shutil.rmtree(path) while os.path.exists(path): pass print('done')

m0z4rt

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)

Lalithesh

파일 삭제:

 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)

전체 디렉토리 트리를 제거하려면 shutil.rmtree() 사용할 수 있습니다. os.rmdir 은 디렉토리가 비어 있고 존재할 때만 작동합니다.

부모에 대해 재귀 적으로 폴더를 삭제하려면 다음을 수행하십시오.

 os.removedirs(name)

일부 콘텐츠가 있는 부모가 될 때까지 self가 있는 모든 빈 부모 디렉터리를 제거합니다.

전. os.removedirs('abc/xyz/pqr')는 디렉토리가 비어 있는 경우 'abc/xyz/pqr', 'abc/xyz' 및 'abc' 순서로 디렉토리를 제거합니다.

더 자세한 정보는 공식 문서를 확인하세요: os.unlink , os.remove , os.rmdir , shutil.rmtree , os.removedirs


Somnath Muluk

폴더의 모든 파일을 제거하려면

 import os import glob files = glob.glob(os.path.join('path/to/folder/*')) files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder for file in files: os.remove(file)

디렉토리의 모든 폴더를 제거하려면

 from shutil import rmtree import os // os.path.join() # current working directory. for dirct in os.listdir(os.path.join('path/to/folder')): rmtree(os.path.join('path/to/folder',dirct))

Sarender Reddy

Éric Araujo의 comment 에 의해 강조 표시된 TOCTOU 문제를 피하기 위해 올바른 메서드를 호출하는 예외를 잡을 수 있습니다.

 def remove_file_or_dir(path: str) -> None: """ Remove a file or directory """ try: shutil.rmtree(path) except NotADirectoryError: os.remove(path)

shutil.rmtree() 는 디렉토리만 제거하고 os.remove() 또는 os.unlink() 는 파일만 제거하기 때문입니다.


Isaac Turner

내 개인적인 선호는 pathlib 개체로 작업하는 것입니다. 특히 크로스 플랫폼 코드를 개발하는 경우 파일 시스템과 상호 작용하는 더 파이썬적이고 오류가 덜 발생하는 방법을 제공합니다.

이 경우 pathlib3x를 사용할 수 있습니다. Python 3.6 이상을 위한 최신(이 답변 Python 3.10.a0을 작성한 날짜) Python pathlib의 백포트와 "copy", "copy2"와 같은 몇 가지 추가 기능을 제공합니다. , "카피트리", "rmtree" 등 ...

shutil.rmtree 를 래핑합니다.

 $> python -m pip install pathlib3x $> python >>> import pathlib3x as pathlib # delete a directory tree >>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir') >>> my_dir_to_delete.rmtree(ignore_errors=True) # delete a file >>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt') >>> my_file_to_delete.unlink(missing_ok=True)

github 또는 PyPi 에서 찾을 수 있습니다.


면책 조항: 저는 pathlib3x 라이브러리의 저자입니다.


bitranox

아름답고 읽기 쉬운 코드를 작성하는 subprocess 사용하는 것이 좋습니다.

 import subprocess subprocess.Popen("rm -r my_dir", shell=True)

소프트웨어 엔지니어가 아니라면 Jupyter 사용을 고려해 보십시오. 간단히 bash 명령을 입력할 수 있습니다.

 !rm -r my_dir

전통적으로, 당신이 사용하는 shutil :

 import shutil shutil.rmtree(my_dir)

Miladiouss

출처 : http:www.stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder-in-python

반응형