Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Làm cách nào để xóa một tệp hoặc thư mục trong Python?

Đối với Python 3, để xóa từng tệp và thư mục, hãy sử dụng các phương thức đối tượng

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()
2 và
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()
3
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()
4 tương ứng:

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

Lưu ý rằng bạn cũng có thể sử dụng các đường dẫn tương đối với các đối tượng

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()
4 và bạn có thể kiểm tra thư mục làm việc hiện tại của mình với
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()
6.

Để xóa các tệp và thư mục riêng lẻ trong Python 2, hãy xem phần được dán nhãn bên dưới.

Để xóa một thư mục có nội dung, hãy sử dụng

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()
7 và lưu ý rằng điều này có sẵn trong Python 2 và 3:

from shutil import rmtree

rmtree(dir_path)

Trình diễn

Mới trong Python 3.4 là đối tượng

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()
4.

Hãy sử dụng một để tạo một thư mục và tệp để chứng minh việc sử dụng. Lưu ý rằng chúng tôi sử dụng

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()
9 để tham gia các phần của đường dẫn, điều này hoạt động xung quanh các vấn đề giữa các hệ điều hành và các vấn đề từ việc sử dụng dấu gạch chéo ngược trên Windows (nơi bạn cần tăng gấp đôi các dấu gạch chéo ngược của mình như
>>> file_path.is_file()
True
0 hoặc sử dụng các chuỗi thô, như
>>> file_path.is_file()
True
1) :

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

và bây giờ:

>>> file_path.is_file()
True

Bây giờ chúng ta hãy xóa chúng. Đầu tiên là tệp:

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

Chúng ta có thể sử dụng Globbing để xóa nhiều tệp - trước tiên hãy tạo một vài tệp cho việc này:

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

Sau đó, chỉ lặp lại mô hình toàn cầu:

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

Bây giờ, chứng minh loại bỏ thư mục:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

Điều gì sẽ xảy ra nếu chúng ta muốn xóa một thư mục và mọi thứ trong đó? Đối với trường hợp sử dụng này, hãy sử dụng

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

Hãy tạo lại thư mục và tệp của chúng tôi:

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

Và lưu ý rằng

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()
3 không thành công trừ khi nó trống, đó là lý do tại sao RMtree rất thuận tiện:

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

Bây giờ, nhập RMtree và chuyển thư mục vào tiêu tốn:

from shutil import rmtree

rmtree(dir_path)
0

Và chúng ta có thể thấy toàn bộ sự việc đã bị xóa:

from shutil import rmtree

rmtree(dir_path)
1

Python 2

Nếu bạn đang ở trên Python 2, có một bản backport của mô -đun Pathlib có tên PathLib2, có thể được cài đặt với PIP:

from shutil import rmtree

rmtree(dir_path)
2

Và sau đó bạn có thể bí danh thư viện thành

>>> file_path.is_file()
True
4

from shutil import rmtree

rmtree(dir_path)
3

Hoặc chỉ nhập trực tiếp đối tượng

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()
4 (như đã trình bày ở đây):

from shutil import rmtree

rmtree(dir_path)
4

Nếu đó là quá nhiều, bạn có thể xóa các tệp bằng

>>> file_path.is_file()
True
6 hoặc
>>> file_path.is_file()
True
7

from shutil import rmtree

rmtree(dir_path)
5

hoặc

from shutil import rmtree

rmtree(dir_path)
6

Và bạn có thể xóa các thư mục bằng

>>> file_path.is_file()
True
8:

from shutil import rmtree

rmtree(dir_path)
7

Lưu ý rằng cũng có một

>>> file_path.is_file()
True
9 - nó chỉ loại bỏ các thư mục trống một cách đệ quy, nhưng nó có thể phù hợp với trường hợp sử dụng của bạn.

Trong bài viết này, chúng tôi sẽ đề cập đến cách xóa (xóa) các tệp và thư mục trong Python. Python cung cấp các phương pháp và chức năng khác nhau để xóa các tệp và thư mục. Người ta có thể xóa tệp theo nhu cầu của họ. & NBSP;

Các phương pháp khác nhau được cung cấp bởi Python là -

  • Sử dụng OS.Remove ()
  • Sử dụng OS.RMDIR ()
  • Sử dụng swutil.rmtree ()
  • Sử dụng pathlib.path (dlank_dir_path) .rmdir ()

Xóa tệp/Dir bằng phương thức Os.Remove ()

Mô -đun HĐH trong Python cung cấp các chức năng để tương tác với hệ điều hành. Tất cả các chức năng trong mô -đun HĐH đều tăng Oserror trong trường hợp tên và đường dẫn tệp không hợp lệ hoặc không thể truy cập hoặc các đối số khác có loại chính xác nhưng không được hệ điều hành chấp nhận. & NBSP; in Python provides functions for interacting with the operating system. All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system. 

Phương thức OS.Remove () trong Python được sử dụng để xóa hoặc xóa đường dẫn tệp. Phương pháp này không thể xóa hoặc xóa một thư mục. Nếu đường dẫn được chỉ định là một thư mục thì Oserror sẽ được đưa ra bằng phương pháp. is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

Cú pháp của Os.Remove ()

Cú pháp: os.remove (đường dẫn, *, dir_fd = none) & nbsp; os.remove(path, *, dir_fd = None) 

Tham số: Đường dẫn: Một đối tượng giống như đường dẫn biểu thị đường dẫn tệp. Một đối tượng giống như đường dẫn là một đối tượng chuỗi hoặc byte đại diện cho một đường dẫn. & Nbsp; path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path. 

  • DIR_FD (Tùy chọn): Một mô tả tệp đề cập đến một thư mục. Giá trị mặc định của tham số này là không có. Nếu đường dẫn được chỉ định là tuyệt đối thì dir_fd bị bỏ qua. & Nbsp;A file descriptor referring to a directory. The default value of this parameter is None. If the specified path is absolute then dir_fd is ignored. 

Lưu ý: Danh sách tham số ‘*trong danh sách tham số chỉ ra rằng tất cả các tham số sau (ở đây trong trường hợp của chúng tôi‘ DIR_FD,) là các tham số chỉ dành cho từ khóa và chúng có thể được cung cấp bằng tên của chúng, không làm tham số vị trí. & NBSP; The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter. 

Loại trả về: Phương thức này không trả về bất kỳ giá trị nào.This method does not return any value.

Ví dụ 1: Xóa một tệp trong Python

Giả sử tệp có trong thư mục là: & nbsp;

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Chúng tôi muốn xóa File1 khỏi thư mục trên. Dưới đây là việc thực hiện. & NBSP;

Python3

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

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

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
2
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

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

Output:  

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Ví dụ 2: Xóa tệp bằng đường dẫn tuyệt đối

Nếu đường dẫn được chỉ định là một thư mục. & Nbsp;

Python3

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

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

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
2
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

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

Ví dụ 2: Xóa tệp bằng đường dẫn tuyệt đối

Output:

from shutil import rmtree

rmtree(dir_path)
8

Nếu đường dẫn được chỉ định là một thư mục. & Nbsp; Check if File Exists Before Deleting

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
8

Python3

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

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

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
9
file_path.parent.mkdir()
file_path.touch()
0

file_path.parent.mkdir()
file_path.touch()
1
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
3

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
2
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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'
3

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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
9
>>> 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'
7
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

Output:

from shutil import rmtree

rmtree(dir_path)
9

Ví dụ 2: Xóa tệp bằng đường dẫn tuyệt đốiTo know more about os.remove() click here.

Nếu đường dẫn được chỉ định là một thư mục. & Nbsp;

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
8OSError will be raised if the specified path is not an empty directory.

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2
os.rmdir(path, *, dir_fd = None) 

Parameter:  

  • >>> 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
    
    8
    >>> 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
    
    9
    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    0
    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    1
    >>> (directory_path / 'foo.my').touch()
    >>> (directory_path / 'bar.my').touch()
    
    6
    >>> (directory_path / 'foo.my').touch()
    >>> (directory_path / 'bar.my').touch()
    
    2
    A path-like object representing a file path. A path-like object is either a string or bytes object representing a path. 
  • DIR_FD (Tùy chọn): Một mô tả tệp đề cập đến một thư mục. Giá trị mặc định của tham số này là không có. Nếu đường dẫn được chỉ định là tuyệt đối thì dir_fd bị bỏ qua. & Nbsp; A file descriptor referring to a directory. The default value of this parameter is None. If the specified path is absolute then dir_fd is ignored. 

Lưu ý: Danh sách tham số ‘*trong danh sách tham số chỉ ra rằng tất cả các tham số sau (ở đây trong trường hợp của chúng tôi‘ DIR_FD,) là các tham số chỉ dành cho từ khóa và chúng có thể được cung cấp bằng tên của chúng, không làm tham số vị trí. & NBSP; The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter. 

Loại trả về: Phương thức này không trả về bất kỳ giá trị nào. This method does not return any value.

Ví dụ 1: Xóa một tệp trong Python Delete all directories from a Directory

Giả sử tệp có trong thư mục là: & nbsp;

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Chúng tôi muốn xóa File1 khỏi thư mục trên. Dưới đây là việc thực hiện. & NBSP;

Python3

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

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

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
2
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

from shutil import rmtree

rmtree(dir_path)
10

Output:  

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Ví dụ 2: Xóa tệp bằng đường dẫn tuyệt đối

Nếu đường dẫn được chỉ định là một thư mục. & Nbsp;

Python3

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

from shutil import rmtree

rmtree(dir_path)
01
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
15

from shutil import rmtree

rmtree(dir_path)
04
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
06

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
09

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
9
file_path.parent.mkdir()
file_path.touch()
0

file_path.parent.mkdir()
file_path.touch()
1
from shutil import rmtree

rmtree(dir_path)
10

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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
9
from shutil import rmtree

rmtree(dir_path)
29
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
1
from shutil import rmtree

rmtree(dir_path)
31

file_path.parent.mkdir()
file_path.touch()
9
>>> 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'
0

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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'
3

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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
9
from shutil import rmtree

rmtree(dir_path)
40
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
1
from shutil import rmtree

rmtree(dir_path)
31

Output:

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

Lưu ý: Để biết thêm về OS.RMDIR () Bấm vào đây. To know more about os.rmdir() click here.

Xóa tệp/DIR bằng cách sử dụng Shutil.rmtree ()

SOWN.RMTREE () được sử dụng để xóa toàn bộ cây thư mục, đường dẫn phải trỏ đến một thư mục (nhưng không phải là một liên kết tượng trưng đến một thư mục).

Cú pháp của SOWL.RMTREE ()

Cú pháp: shutil.rmtree (đường dẫn, bỏ qua_errors = false, onerror = none) & nbsp; shutil.rmtree(path, ignore_errors=False, onerror=None) 

Parameters:  

  • Đường dẫn: Một đối tượng giống như đường dẫn đại diện cho một đường dẫn tệp. Một đối tượng giống như đường dẫn là một đối tượng chuỗi hoặc byte đại diện cho một đường dẫn. & Nbsp;A path-like object representing a file path. A path-like object is either a string or bytes object representing a path. 
  • bỏ qua_errors: Nếu bỏ qua_errors là đúng, các lỗi do loại bỏ không thành công sẽ bị bỏ qua. & nbsp; If ignore_errors is true, errors resulting from failed removals will be ignored. 
  • Onerror: Nếu bỏ qua_error là sai hoặc bị bỏ qua, các lỗi đó được xử lý bằng cách gọi một trình xử lý được chỉ định bởi Onerror. If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

Xóa một thư mục và các tệp có trong đó.

Ví dụ 1: & nbsp; 

Giả sử thư mục và các thư mục phụ như sau.

& nbsp;# thư mục cha mẹ: & nbsp;# Parent directory: 

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

& nbsp;# thư mục bên trong thư mục mẹ: & nbsp;# Directory inside parent directory: 

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

# Tệp bên trong thư mục phụ: & nbsp; 

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Ví dụ: Xóa tất cả các tệp khỏi thư mục

Chúng tôi muốn loại bỏ các tác giả thư mục. Dưới đây là việc thực hiện. & NBSP;

Python3

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
0
from shutil import rmtree

rmtree(dir_path)
44

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
5
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
49

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
52

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

from shutil import rmtree

rmtree(dir_path)
58

Output:  

Hướng dẫn how do i delete a full directory in python? - làm cách nào để xóa một thư mục đầy đủ trong python?

Ví dụ 2: Bỏ qua lỗi trong khi xóa thư mục

Bằng cách vượt qua bỏ qua_errors = true. & Nbsp;

Python3

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
0
from shutil import rmtree

rmtree(dir_path)
44

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
5
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
49

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
52

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

from shutil import rmtree

rmtree(dir_path)
74
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
76
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

Output:

Ví dụ 2: Bỏ qua lỗi trong khi xóa thư mục

Bằng cách vượt qua bỏ qua_errors = true. & Nbsp;

Traceback (cuộc gọi gần đây nhất cuối cùng): File \ Chương trình \ Python \ Python38-32 \ lib \ shatil.py, dòng 730, trong rmtree return _rmtree_unsafe (path, onerror) File lib \ swutil.py, dòng 589, trong _rmtree_unsafe onerror (os.scandir, path, sys.exc_info ()) Shutil.py, dòng 586, trong _rmtree_unSafe với Os.Scandir (đường dẫn) dưới dạng scandir_it: filenotfounderror: [WinError 3] Hệ thống không thể tìm thấy đường dẫn được chỉ định: '

  • Ví dụ 3: Trình xử lý ngoại lệfunction which raised the exception.
  • Trong OnError, hàm nên được truyền phải chứa ba tham số. path name passed which raised the exception while removal
  • Chức năng - Chức năng nâng cao ngoại lệ. exception info raised by sys.exc_info()

Đường dẫn - tên đường dẫn được truyền đi trong khi loại bỏ

Python3

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
0
from shutil import rmtree

rmtree(dir_path)
44

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
5
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
49

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
>>> 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
9
from shutil import rmtree

rmtree(dir_path)
87
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

file_path.parent.mkdir()
file_path.touch()
1
>>> 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
8
from shutil import rmtree

rmtree(dir_path)
91

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
5
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
49

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

rmtree(dir_path)
52

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

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()
03
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
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()
05

Output:

Ví dụ 2: Bỏ qua lỗi trong khi xóa thư mục

Bằng cách vượt qua bỏ qua_errors = true. & Nbsp;

Traceback (cuộc gọi gần đây nhất cuối cùng): File \ Chương trình \ Python \ Python38-32 \ lib \ shatil.py, dòng 730, trong rmtree return _rmtree_unsafe (path, onerror) File lib \ swutil.py, dòng 589, trong _rmtree_unsafe onerror (os.scandir, path, sys.exc_info ()) Shutil.py, dòng 586, trong _rmtree_unSafe với Os.Scandir (đường dẫn) dưới dạng scandir_it: filenotfounderror: [WinError 3] Hệ thống không thể tìm thấy đường dẫn được chỉ định: '

Ví dụ 3: Trình xử lý ngoại lệ

Trong OnError, hàm nên được truyền phải chứa ba tham số.

Parameter:  

  • Chức năng - Chức năng nâng cao ngoại lệ. A path-like object representing a empty directory path. A path-like object is either a string or bytes object representing a path. 

Đường dẫn - tên đường dẫn được truyền đi trong khi loại bỏ This method does not return any value.

ExcInfo - Thông tin ngoại lệ được nêu bởi sys.exc_info ()

Dưới đây là triển khai & NBSP;

Python3

from shutil import rmtree

rmtree(dir_path)
82
from shutil import rmtree

rmtree(dir_path)
83

Bên trong Handler (, FilenotFounderror (2, System Hệ thống không thể tìm thấy đường dẫn được chỉ định),) bên trong Handler (, FilenotFounderror (2, System Hệ thống không thể tìm thấy tệp được chỉ định),)

Xóa tệp/Dir

Một thư mục trống cũng có thể được xóa hoặc xóa bằng phương thức Module PathLib Module RMDIR (). Đầu tiên, chúng tôi phải & nbsp; đặt đường dẫn cho thư mục, và sau đó chúng tôi & nbsp; gọi phương thức rmdir () trên đường dẫn đó

Output:

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

Làm cách nào để xóa toàn bộ thư mục?

Để xóa một thư mục và tất cả các nội dung của nó, bao gồm mọi thư mục con và tệp, hãy sử dụng lệnh RM với tùy chọn đệ quy, -r.Các thư mục được xóa bằng lệnh RMDIR không thể được phục hồi, các thư mục cũng không thể bị xóa nội dung của chúng bằng lệnh RM -R.use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

Phương pháp nào được sử dụng để xóa một thư mục trong Python?

Xóa thư mục (thư mục) trong Python bạn có thể sử dụng hệ điều hành.rmdir () và pathlib.Đường dẫn.rmdir () để xóa một thư mục trống và im lặng.