programing

Python에서 파일이나 폴더를 삭제하려면 어떻게 해야 하나요?

javaba 2022. 9. 16. 21:58
반응형

Python에서 파일이나 폴더를 삭제하려면 어떻게 해야 하나요?

파일 또는 폴더를 삭제하려면 어떻게 해야 합니까?


Path Python 3.4+ 모듈의 객체도 다음 인스턴스 메서드를 노출합니다.

파일을 삭제하는 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)

파일 또는 심볼릭 링크를 제거하는 데 사용되는 연결 해제 메서드입니다.

이 false인 경우 합니다.missing_ok' false(')는 FileNotFoundError'가 발생합니다.
missing_ok' true' FileNotFoundError' (POSIX rm -f ')
3.8일: missing_ok일 것 같다.

베스트 프랙티스

  1. 먼저 파일 또는 폴더가 있는지 확인한 후 해당 파일만 삭제합니다.은 두 수 . 즉, 두 가지 방법이 있습니다.
    a. a.os.path.isfile("/path/to/file")
    b. 를 사용합니다.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에러: 데모.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))

사용하다

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

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

os.remove

그리고.

os.rmdir

(OS에 관한 완전한 문서).

에서는 두 가지 기능을 모두 줍니다.os.remove ★★★★★★★★★★★★★★★★★」shutil.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))

내장 모듈을 사용할 수 있습니다(Python 3.4+가 필요하지만 PyPI: , 이전 버전의 백포트가 있습니다).

파일을 삭제하는 방법은 다음과 같습니다.

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

또는 빈 폴더를 삭제하는 방법:

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

Python에서 파일이나 폴더를 삭제하려면 어떻게 해야 하나요?

Python 3 의 경우는, 파일과 디렉토리를 개별적으로 삭제하려면 , 및 를 사용합니다. 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에서 개별 파일 및 디렉터리를 제거하려면 아래 레이블이 지정된 섹션을 참조하십시오.

컨텐츠가 있는 디렉토리를 삭제하려면 , 를 사용해 주세요.이 디렉토리는 Python 2 및 3에서 사용할 수 있습니다.

from shutil import rmtree

rmtree(dir_path)

데모

3.은 Python 3.4입니다.Path★★★★★★ 。

그 중 하나를 사용하여 디렉토리 및 파일을 생성하여 사용법을 보여 줍니다.「」를 하고 있는 ./패스의 하려면 , 의 사용에 ( 「」와 같이, 업 할).\\string을 를 들어, raw string 을 합니다.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

globing을 사용하여 여러 파일을 삭제할 수 있습니다.먼저 몇 개의 파일을 만듭니다.

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

디렉토리 및 그 안에 있는 모든 것을 삭제하려면 어떻게 해야 합니까?예에서는, 「」를 합니다.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를 Import하여 디렉토리를 함수에 전달합니다.

from shutil import rmtree
rmtree(directory_path)      # remove everything 

모든 것이 제거되었음을 알 수 있습니다.

>>> directory_path.exists()
False

파이썬 2

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

$ pip install pathlib2

을 '출석하다'로 수 있습니다.pathlib

import pathlib2 as pathlib

직접 만 하면 .Path오브젝트(여기서 설명한 바와 같이):

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

또, 다음과 같이 디렉토리를 삭제할 수 있습니다.

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

빈 디렉토리는 재귀적으로만 삭제되지만 사용 예에 적합할 수 있습니다.

Python에서 파일 또는 폴더 삭제

Python에서 파일을 삭제하는 방법은 여러 가지가 있지만 가장 좋은 방법은 다음과 같습니다.

  1. os.remove()는 파일을 삭제합니다.
  2. os.unlink()는 파일을 삭제합니다.remove() 메서드의 Unix 이름입니다.
  3. shutil.rmtree()는 디렉토리와 디렉토리의 모든 내용을 삭제합니다.
  4. pathlib.Path.unlink()는 단일 파일을 삭제합니다. Python 3.4 이상에서 pathlib 모듈을 사용할 수 있습니다.

os.remove()

예 1: os.remove() 메서드를 사용하여 파일을 삭제하는 기본적인 예.

import os
os.remove("test_file.txt")
print("File removed successfully")

예 2: os.path.isfile을 사용하여 파일이 존재하는지 확인하고 os.remove를 사용하여 파일을 삭제합니다.

import os
#checking if file exist or not
if(os.path.isfile("test.txt")):
    #os.remove() function to remove the file
    os.remove("test.txt")
    #Printing the confirmation message of deletion
    print("File Deleted successfully")
else:
print("File does not exist")
#Showing the message instead of throwig an error

예 3: 특정 확장자를 가진 모든 파일을 삭제하는 Python 프로그램

import os 
from os import listdir
my_path = 'C:\Python Pool\Test\'
for file_name in listdir(my_path):
    if file_name.endswith('.txt'):
        os.remove(my_path + file_name)

예 4: 폴더 내의 모든 파일을 삭제하는 Python 프로그램

특정 디렉토리 내의 모든 파일을 삭제하려면 * 기호를 패턴 문자열로 사용하면 됩니다.#os 및 glob 모듈의 Import, glob #Loop 폴더는 모든 파일을 투영하여 glob.glob("pythonpool/*") 내의 파일에 대해 하나씩 삭제합니다.os.remove(file) print("삭제된 " + str(file)"

os.unlink()

os.unlink()는 os.remove()의 에일리어스 또는 다른 이름입니다.유닉스 OS에서와 같이 삭제는 unlink라고도 합니다.주의: 모든 기능과 구문은 os.unlink() 및 os.remove()와 동일합니다.둘 다 Python 파일 경로를 삭제하는 데 사용됩니다.둘 다 Python 표준 라이브러리의 os 모듈에서 삭제 기능을 수행하는 메서드입니다.

shutil.rmtree()

예 1: shutil.rmtree()를 사용하여 파일을 삭제하는 Python 프로그램

import shutil 
import os 
# location 
location = "E:/Projects/PythonPool/"
# directory 
dir = "Test"
# path 
path = os.path.join(location, dir) 
# removing directory 
shutil.rmtree(path) 

예 2: shutil.rmtree()를 사용하여 파일을 삭제하는 Python 프로그램

import shutil 
import os 
location = "E:/Projects/PythonPool/"
dir = "Test"    
path = os.path.join(location, dir) 
shutil.rmtree(path) 

pathlib.빈 디렉토리를 삭제하는 Path.rmdir()

Pathlib 모듈에서는 다양한 방법으로 파일을 조작할 수 있습니다.Rmdir는 빈 폴더를 삭제할 수 있는 경로 함수 중 하나입니다.먼저 디렉토리의 Path()를 선택해야 합니다.그 후 rmdir() 메서드를 호출하면 폴더 크기가 체크됩니다.비어 있으면 삭제됩니다.

이는 실제 데이터를 잃지 않고 빈 폴더를 삭제할 수 있는 좋은 방법입니다.

from pathlib import Path
q = Path('foldername')
q.rmdir()

shutil.rmtree는 비동기 함수이므로 언제 완료되는지 확인하려면 다음 중 사용할 수 있습니다.고리

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')
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)

이것은 dir를 삭제하는 기능입니다."경로"에는 전체 경로 이름이 필요합니다.

import os

def rm_dir(path):
    cwd = os.getcwd()
    if not os.path.exists(os.path.join(cwd, path)):
        return False
    os.chdir(os.path.join(cwd, path))

    for file in os.listdir():
        print("file = " + file)
        os.remove(file)
    print(cwd)
    os.chdir(cwd)
    os.rmdir(os.path.join(cwd, path))

파일을 삭제하는 경우:

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)

컨텐츠가 있는 부모까지, 자기 자신을 포함한 모든 빈 부모 디렉토리를 삭제합니다.

예: os.svsirsssvs/xyz/pqr')는 디렉토리가 비어 있는 경우 'svs/xyz/pqr', 'svs/xyz', 'svs/xyz' 순으로 디렉토리를 삭제합니다.

자세한 내용은 공식 문서를 참조하십시오: , , , , , .

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

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

Eric Araujo의 코멘트로 강조된 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() 및 렉 will will will remove remove remove remove remove remove remove remove remove 만 삭제됩니다.os.remove() ★★★★★★★★★★★★★★★★★」os.unlink()파일만 삭제합니다.

개인적으로는 pathlib 객체를 사용하는 것을 선호합니다.특히 크로스 플랫폼 코드를 개발하는 경우 파일 시스템과 상호 작용하기 위한 보다 피토닉하고 오류 발생률이 낮은 방법을 제공합니다.

이 경우 pathlib3x를 사용할 수 있습니다.- Python 3.6 또는 그 이후를 위한 최신 Python 3.10.a0의 백포트와 "copy", "copy2", "copytree", "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 라이브러리의 작성자입니다.

폴더에서 파일을 삭제하는 방법은 크게 4가지입니다.

방법 1

os.remove()

다른 3가지 메서드의 코드를 가져옵니다.

를 사용하는 것을 추천합니다.subprocess아름답고 읽기 쉬운 코드를 쓰는 것이 마음에 든다면:

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

소프트웨어 엔지니어가 아닌 경우 Jupyter 사용을 고려해 보십시오.bash 명령어를 입력하기만 하면 됩니다.

!rm -r my_dir

기존에는shutil:

import shutil
shutil.rmtree(my_dir) 

언급URL : https://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python

반응형