파일이나 폴더를 삭제하려면

:에서이 번역 삭제 파일 또는 폴더

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


# 1 층

참조 : https://stackoom.com/question/TM8R/ 파일이나 폴더를 삭제


하우스 # 2

. 너희들의 기능을 만들기 당신을위한 함수를 만듭니다.

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

하우스 # 3

파일 삭제 파이썬 구문 파일 삭제에 사용되는 파이썬 구문

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

또는

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

모범 사례 모범 사례

  1. 첫째, 파일이나 폴더가 있는지 여부를 확인 존재하거나 다음 해당 파일을 삭제할 수 없습니다. 먼저, 그럼 그냥 파일을 삭제, 파일 또는 폴더 존재를 확인합니다. 이 두 가지 방법으로 달성 될 수있다 : 그것은 두 가지 방법으로 달성 할 수 있습니다
    . 가. os.path.isfile("/path/to/file")
    나. 베이 를 사용하여 exception handling. 사용exception handling.

에 대한 os.path.isfile 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를

파이썬은 폴더를 삭제 구문 파이썬 구문은 폴더를 삭제하기

shutil.rmtree()

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

# 4 층

내장에서의 당신에 의한 CAN 사용 pathlib모듈합니다 (파이썬 3.4 이상이 필요하지만, 이전 버전에 대한 백 포트가 PyPI ON있다 : pathlib, pathlib2). 당신은 내장에서 사용할 수있는 pathlib모듈 (파이썬 3.4 이상,하지만 PyPI에서 이전 버전이 필요합니다 pathlib: pathlib, pathlib2) .

제거 상기받는 사람이있는 파일 unlink방법, : 파일을 삭제하려면, 사용 unlink방법 :

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

수술실에서 rmdir방법, 제거하기는 비어 폴더 : 또는 삭제 폴더 rmdir방법 :

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

하우스 # 5

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)

하우스 # 6

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

3 파이썬의 경우는, 사용에서 개별 파일 및 디렉토리에 제거에 unlink각각 객체 방법 : rmdir Path 파이썬 3를 들어, 삭제 파일을 원하는 디렉토리는 각각 사용할 수 있습니다 unlink개체 방법 :rmdir 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. 당신은 또한 사용할 수 있습니다 Path상대 경로 객체 및 사용할 수있는 Path.cwd현재 작업 디렉토리를 확인합니다.

파이썬에서 개별 파일 및 디렉토리를 제거하기위한 2. 그래서 아래에 표시된 섹션을 참조 단일 파일 및 디렉토리 2 파이썬을 삭제하려면 다음 태그 섹션을 참조하십시오.

제거받는 사람, 사용을 가진 디렉토리 내용 shutil.rmtree다음이 파이썬 2와 3에서 사용할 수 있는지, 그리고 주 내용, 사용을 포함하는 디렉토리를 삭제하려면 shutil.rmtree이 파이썬 2와 3에서 사용할 수 있는지, 그리고 참고 :

from shutil import rmtree

rmtree(dir_path)

데모 데모

파이썬 3.4의 새로운에서 IS Path개체입니다. 파이썬 3.4의 새로운 기능은 Path객체.

의 디렉토리 생성을 사용하자 사용법을 설명하고 파일을. 우리는 디렉토리와 사용법을 설명 할 파일을 만들어 보자. 우리는 노트에 사용하는 /1, 경로에서의 부품에 가입하는이 작품 운영 체제 및 (당신처럼 하나를 두 번 백 슬래시 필요하려는 사용하여 Windows에서와 비행과 비행 간의 ON-백 슬래시 주위 \\\\, 또는 사용 RAW 문자열 등 r"foo\\bar") : 공지 사항 우리가 사용하는 /(당신이 같은 이중 백 슬래시,해야하는 운영 체제 및 Windows에서 백 슬래시를 사용하는 문제 사이의 문제를 해결 연결 경로의 여러 부분을 \\\\같은 원래 문자열 또는 사용 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

우리는 여러 파일을 제거하는 글 로빙을 사용할 수 있습니다 : 첫 번째의이에 대한 몇 가지 파일을 만들 수 있습니다 - 우리는 삭제 여러 개의 파일을 글 로빙 사용할 수 있습니다 - 우리가 일부 파일을 만들려면이 해 보자 :

>>> (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 이 유스 케이스, 사용shutil.rmtree

하자 우리의 디렉토리와 파일을 다시 : 하자 재 작성 우리의 디렉토리와 파일 :

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

참고와 rmdirIT가 비어 않는 편리한의 rmtree 왜 SO IS되는, 전 체를 실패 하고 지불 관심을 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/excelsiora/directory'

자, 수입 rmtree 및 디렉토리를 통과 연료 소모량에 : 자, 가져 오기 및 rmtree 디렉토리가 연료 소모량에 전달 :

from shutil import rmtree
rmtree(directory_path)      # remove everything 

우리는 모든 일이있다 볼 수 있습니다 제거 : 우리는 모든 일이 삭제되었습니다 볼 수 있습니다 :

>>> directory_path.exists()
False

파이썬이 파이썬 2

당신은이 파이썬 IF에있어하는 거기 라는 pathlib 모듈에서 pathlib2의 백 포트 : 핍 설치할 수 있습니다, 당신은 파이썬 2를 사용하는 경우, 거기에있을 것입니다 pathlib 모듈의 이름 pathlib2백 포트 를 사용 핍이 될 수는 설치 :

$ pip install pathlib2

그리고 당신은에 라이브러리를 별칭 수 pathlib 다음 수 별칭 라이브러리pathlib

import pathlib2 as pathlib

가져 오기 단지는 직접 또는 Path: 개체 (AS 여기에 배경 화면을 시연) 또는 직접에 Path(다음과 같이) 객체 :

from pathlib2 import Path

너무 많은 즉, IF는 당신이 파일은 제거와 함께, CAN의 os.remove또는os.unlink 너무 많은이 경우, 당신은 사용할 수 있습니다 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: 당신이 할 수 os.rmdir있는 디렉토리를 삭제합니다 :

from os import rmdir

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

또한 참고 사항이 있다는 것을 os.removedirs-. 난 단지 제거합니다 디렉토리 재귀를 비울 수 있지만 SUIT는 사용에 IT-케이스 하시기 바랍니다 노트는이 있음 os.removedirs- 그것은 반복적으로 바로 삭제 빈 디렉토리를, 그러나 그것은 당신의 유스 케이스에 적합 할 수있다.

원저 0 출판 · 원 찬양 136 · 전망 830 000 +

추천

출처blog.csdn.net/xfxf996/article/details/105192685