Hướng dẫn delete file in folder python - xóa tập tin trong thư mục 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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
2 và
>>> 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 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

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

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

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
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 bạn như
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
0 hoặc sử dụng các chuỗi thô, như
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
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

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

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
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 "", line 1, in 
  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

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

from shutil import rmtree

rmtree(dir_path)
3

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

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

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
6 hoặc
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
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

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

from shutil import rmtree

rmtree(dir_path)
7

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

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
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 hướng dẫn này, bạn sẽ học cách xóa các tệp hoặc thư mục trong Python.

Sau khi đọc hướng dẫn này, bạn sẽ học: -: –

  • Xóa tệp bằng mô -đun HĐH và mô -đun Pathlib
  • Xóa các tệp khỏi thư mục
  • Xóa các tệp phù hợp với mẫu (ký tự đại diện)
  • Xóa thư mục trống
  • Xóa nội dung của một thư mục (tất cả các tệp và thư mục phụ)

Đôi khi chúng ta cần xóa các tệp khỏi một thư mục không còn cần thiết. Ví dụ: bạn đang lưu trữ dữ liệu hàng tồn kho hàng tháng trong một tệp. Bạn có thể muốn xóa bất kỳ tệp dữ liệu hiện có nào trước khi tạo tệp dữ liệu mới mỗi tháng.

Ngoài ra, sau một thời gian, ứng dụng cần xóa các tệp nhật ký cũ của nó.

Trong hướng dẫn này, chúng tôi sẽ sử dụng các hàm Python sau đây để xóa các tệp và thư mục.Python functions to delete files and folders.

Hàm sốSự mô tả
>>> 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
0
Xóa tệp được chỉ định.
>>> 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
1
Xóa tệp được chỉ định. Hữu ích trong môi trường Unix.
>>> 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
2
Xóa tệp hoặc liên kết tượng trưng trong đường dẫn đã đề cập
>>> 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
3
Xóa thư mục trống.
>>> 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
4
Khóc và xóa thư mục trống.
>>> 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
5
Xóa một thư mục và các tệp có trong đó.
Các chức năng để xóa các tệp và thư mục

Ghi chú::

  • Tất cả các chức năng trên xóa các tệp và thư mục vĩnh viễn.
  • Mô -đun Pathlib đã được thêm vào trong Python 3.4. Nó là phù hợp khi ứng dụng của bạn chạy trên một hệ điều hành khác.

Cách xóa một tệp trong Python

Python cung cấp hỗ trợ mạnh mẽ cho việc xử lý tệp. Chúng ta có thể xóa các tệp bằng các phương thức khác nhau và phương pháp được sử dụng phổ biến nhất là phương thức

>>> 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
6. Dưới đây là các bước để xóa một tập tin.

  1. Tìm đường dẫn của một tệp

    Chúng ta có thể xóa một tệp bằng cả đường dẫn tương đối và đường dẫn tuyệt đối. Đường dẫn là vị trí của tệp trên đĩa. Một đường dẫn tuyệt đối chứa danh sách thư mục hoàn chỉnh cần thiết để định vị tệp. Và một đường dẫn tương đối bao gồm thư mục hiện tại và sau đó là tên tệp. Ví dụ, & nbsp; ________ 67 & nbsp; là một đường dẫn tuyệt đối để khám phá các mẫu.txt.
    An absolute path contains the complete directory list required to locate the file. And A relative path includes the current directory and then the file name.
    For example, 

    >>> 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
    
    7 is an absolute path to discover the samples.txt.

  2. Sử dụng hàm Os.Remove () để xóa tệp

    Mô -đun HĐH trong Python cung cấp các phương pháp để tương tác với hệ điều hành trong Python. Phương thức ________ 68 () trong mô -đun này được sử dụng để xóa/xóa đường dẫn tệp. Đầu tiên, hãy nhập mô -đun HĐH và chuyển đường dẫn tệp đến hàm

    >>> 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
    
    0 để xóa tệp khỏi đĩa
    First, import the os module and Pass a file path to the
    >>> 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
    
    0 function to delete a file from a disk

  3. Sử dụng hàm rmtree () của mô -đun SHOTIL để xóa thư mục

    Nhập mô -đun SHOTIL và chuyển đường dẫn thư mục đến hàm

    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    0 để xóa thư mục và tất cả các tệp có trong đó.

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

Mã sau đây giải thích cách xóa một tệp có tên là Sales Sales_1.txt.

Hãy giả sử chúng tôi muốn xóa tệp sales_1.txt khỏi thư mục

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
1. Ngay bây giờ, thư mục này chứa các tệp sau:

  1. sales_1.txt
  2. sales_2.csv
  3. profits.txt
  4. revenue.txt

Xóa tệp có đường dẫn tương đối

from shutil import rmtree

rmtree(dir_path)
8

Xóa tệp bằng đường dẫn tuyệt đối

from shutil import rmtree

rmtree(dir_path)
9

Mã của chúng tôi đã xóa hai tập tin. Dưới đây là danh sách các tệp còn lại trong thư mục của chúng tôi:

  • profits.txt
  • doanh thu.txt

Syntax::

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

Chuyển đường dẫn tệp đến hàm

>>> 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
0 để xóa tệp khỏi đĩa to the
>>> 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
0 function to delete a file from a disk

Sau đây là các tham số mà chúng ta cần vượt qua.

  • Đường dẫn - Một đường dẫn tương đối hoặc tuyệt đối cho đối tượng tệp thường ở định dạng chuỗi. – A relative or absolute path for the file object generally in string format.
  • DIR_FD - Một thư mục đại diện cho vị trí của tệp. Giá trị mặc định là không có và giá trị này bị bỏ qua trong trường hợp đường dẫn tuyệt đối. – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.

Nếu đường dẫn tệp được truyền là một thư mục, một

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
4 sẽ được nâng lên

Kiểm tra xem tệp có tồn tại trước khi xóa nó không

Một

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
5 sẽ được nêu ra nếu tệp không được tìm thấy trong đường dẫn nên nên kiểm tra xem tệp có tồn tại trước khi xóa nó không.

Điều này có thể đạt được theo hai cách:

  • >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    6 Hàm để kiểm tra xem tệp có tồn tại không.
  • Sử dụng xử lý ngoại lệ.

Ví dụ 1: 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()
1

LƯU Ý: Xử lý ngoại lệ được khuyến nghị qua kiểm tra tệp vì tệp có thể bị xóa hoặc thay đổi ở giữa. Đó là cách pythonic để xóa một tệp có thể hoặc không tồn tại.: Exception handling is recommended over file check because the file could be removed or changed in between. It is the Pythonic way to delete a file that may or may not exist.

Ví dụ 2: Xử lý ngoại lệ: Exception handling

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

Xóa tệp bằng phương pháp >>> directory_path.rmdir() # remove directory >>> directory_path.is_dir() False >>> directory_path.exists() False 7

Nếu bạn đang sử dụng hệ điều hành UNIX, hãy sử dụng phương thức

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
8 có sẵn trong mô -đun
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
9, tương tự như Remove () ngoại trừ việc nó quen thuộc hơn trong môi trườ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
  • Đường dẫn - Một đường dẫn tương đối hoặc tuyệt đối cho đối tượng tệp thường ở định dạng chuỗi. – A relative or absolute path for the file object generally in string format.
  • DIR_FD - Một thư mục đại diện cho vị trí của tệp. Giá trị mặc định là không có và giá trị này bị bỏ qua trong trường hợp đường dẫn tuyệt đối. – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.

Nếu đường dẫn tệp được truyền là một thư mục, một

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
4 sẽ được nâng lên

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

Kiểm tra xem tệp có tồn tại trước khi xóa nó không

Một

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
5 sẽ được nêu ra nếu tệp không được tìm thấy trong đường dẫn nên nên kiểm tra xem tệp có tồn tại trước khi xóa nó không. need to work with files in multiple environments, we can use the pathlib module.

Điều này có thể đạt được theo hai cách:was added in Python 3.4. The

file_path.parent.mkdir()
file_path.touch()
1 method in the pathlib module is used to remove the file in the mentioned path.

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
6 Hàm để kiểm tra xem tệp có tồn tại không.

Sử dụng xử lý ngoại lệ.

  • Ví dụ 1:
  • LƯU Ý: Xử lý ngoại lệ được khuyến nghị qua kiểm tra tệp vì tệp có thể bị xóa hoặc thay đổi ở giữa. Đó là cách pythonic để xóa một tệp có thể hoặc không tồn tại.
  • Ví dụ 2: Xử lý ngoại lệ
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()
5

Xóa tệp bằng phương pháp >>> directory_path.rmdir() # remove directory >>> directory_path.is_dir() False >>> directory_path.exists() False 7

Nếu bạn đang sử dụng hệ điều hành UNIX, hãy sử dụng phương thức

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
8 có sẵn trong mô -đun
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
9, tương tự như Remove () ngoại trừ việc nó quen thuộc hơn trong môi trường.

  • Hãy cho chúng tôi xem mã để xóa tệp Lợi nhuận.txt, trong đường dẫn thực thi hiện tại.
  • Mô -đun Pathlib để xóa tệp
  • Mô -đun Pathlib cung cấp các lớp đại diện cho các đường dẫn hệ thống tập tin với ngữ nghĩa phù hợp cho các hệ điều hành khác nhau. Do đó, bất cứ khi nào chúng ta cần làm việc với các tệp trong nhiều môi trường, chúng ta có thể sử dụng mô -đun Pathlib.

Example::

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

Mô -đun Pathlib đã được thêm vào trong Python 3.4. Phương thức file_path.parent.mkdir() file_path.touch() 1 trong mô -đun pathlib được sử dụng để xóa tệp trong đường dẫn đã đề cập.

Ngoài ra, phải mất một tham số bổ sung, cụ thể là

file_path.parent.mkdir()
file_path.touch()
2. Nếu tham số được đặt thành TRUE, thì mô -đun PathLib sẽ bỏ qua lỗi không tìm thấy tệp. Mặt khác, nếu con đường không tồn tại, thì
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
5 sẽ được nâng lên.

Hãy cho chúng tôi xem mã để xóa tệp Lợi nhuận.txt, có mặt trong đường dẫn thực thi hiện tại.

Nhập mô -đun Pathlib

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

Sử dụng phương thức

file_path.parent.mkdir()
file_path.touch()
4 để đặt đường dẫn tệp

  • Tiếp theo, để xóa một tệp, hãy gọi phương thức
    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    8 trên đường dẫn tệp đã cho.
  • Xóa tất cả các tệp khỏi một thư mục

Đôi khi chúng tôi muốn xóa tất cả các tệp khỏi thư mục mà không cần xóa thư mục. Thực hiện theo các bước dưới đây để xóa tất cả các tệp từ một thư mục.: In case if the directory is not empty then the

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
4 will be thrown.

Nhận danh sách các tệp trong một thư mục bằng hàm
file_path.parent.mkdir()
file_path.touch()
6. Nó trả về một danh sách chứa tên của các tệp và thư mục trong thư mục đã cho.

Lặp lại trong danh sách bằng cách sử dụng vòng lặp for để truy cập từng tệp một

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

Xóa từng tệp bằng cách sử dụng

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

Xóa một thư mục trống (thư mục) bằng cách sử dụng

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

  • Mặc dù luôn luôn là trường hợp một thư mục có một số tệp, đôi khi có các thư mục hoặc thư mục trống không còn cần thiết. Chúng ta có thể xóa chúng bằng phương pháp
    file_path.parent.mkdir()
    file_path.touch()
    
    8 có sẵn trong cả mô -đun OS và mô -đun Pathlib.
  • Sử dụng phương pháp
    >>> directory_path.rmdir()
    Traceback (most recent call last):
      File "", line 1, in 
      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

Để xóa các thư mục trống, chúng ta có thể sử dụng hàm

file_path.parent.mkdir()
file_path.touch()
8 khỏi mô -đun HĐH.

>>> file_path.is_file()
True
0

Sau đây là các tham số mà chúng ta cần chuyển sang phương pháp này.

>>> directory_path.rmdir()
Traceback (most recent call last):
  File "", line 1, in 
  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'
2 - Một đường dẫn tương đối hoặc tuyệt đối cho đối tượng thư mục thường ở định dạng chuỗi.

Mô-đun Python Shutil giúp thực hiện các hoạt động cấp cao trong một tệp hoặc bộ sưu tập các tệp như sao chép hoặc xóa nội dung.

>>> file_path.is_file()
True
1

Parameters::

  • >>> directory_path.rmdir()
    Traceback (most recent call last):
      File "", line 1, in 
      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'
    
    2 - Thư mục để xóa. Các liên kết tượng trưng đến một thư mục không được chấp nhận.
  • from shutil import rmtree
    
    rmtree(dir_path)
    
    01 - Nếu cờ này được đặt thành TRUE, thì các lỗi do loại bỏ không thành công sẽ bị bỏ qua. Nếu được đặt thành TRUE, lỗi phải được xử lý bởi hàm được truyền trong thuộc tính một lỗi.

Lưu ý: Hàm ____102 xóa thư mục được chỉ định và tất cả các thư mục con của nó đệ quy.: The

from shutil import rmtree

rmtree(dir_path)
02 function deletes the specified folder and all its subfolders recursively.

Xem xét ví dụ sau để xóa thư mục ‘Báo cáo có chứa các tệp hình ảnh và tệp PDF.

>>> file_path.is_file()
True
2

Đầu ra

>>> file_path.is_file()
True
3

Nhận thông báo ngoại lệ thích hợp trong khi xóa thư mục không trống

Để có được thông báo ngoại lệ thích hợp, chúng tôi có thể xử lý nó trong một hàm riêng mà chúng tôi có thể truyền trong tham số

from shutil import rmtree

rmtree(dir_path)
03 hoặc bằng cách bắt nó trong khối Excet Try-Except.

>>> file_path.is_file()
True
4

Mã cuối cùng: Để xóa tệp hoặc thư mục: To delete File or directory

>>> file_path.is_file()
True
5

Xóa các tệp khớp với một mẫu

Ví dụ: bạn muốn xóa các tệp nếu tên chứa một chuỗi cụ thể.

Mô -đun Glob Python, một phần của thư viện tiêu chuẩn Python, được sử dụng để & nbsp; tìm các tệp và thư mục có tên theo một mẫu cụ thể.find the files and folders whose names follow a specific pattern.

>>> file_path.is_file()
True
6

Phương thức

from shutil import rmtree

rmtree(dir_path)
04 trả về danh sách các tệp hoặc thư mục phù hợp với mẫu được chỉ định trong đối số
from shutil import rmtree

rmtree(dir_path)
05.

Hàm này có hai đối số, cụ thể là tên đường dẫn và cờ đệ quy (nếu được đặt thành & nbsp;

Chúng ta có thể sử dụng các ký tự ký tự đại diện để khớp mẫu và sau đây là danh sách các ký tự ký tự đại diện được sử dụng trong khớp mẫu.wildcard characters for the pattern matching, and the following is the list of the wildcard characters used in the pattern matching.

  • Asterisk (
    from shutil import rmtree
    
    rmtree(dir_path)
    
    07): khớp với số không hoặc nhiều ký tự
  • Dấu câu hỏi (
    from shutil import rmtree
    
    rmtree(dir_path)
    
    08) phù hợp với chính xác một ký tự
  • Chúng ta có thể chỉ định một loạt các ký tự chữ và số bên trong & nbsp; ________ 109.

Ví dụ: Xóa các tệp với tiện ích mở rộng cụ thể

Trong những dịp nhất định, chúng tôi phải xóa tất cả các tệp với một tiện ích mở rộng cụ thể.

  • Sử dụng phương thức
    from shutil import rmtree
    
    rmtree(dir_path)
    
    10 để tìm tất cả các tệp văn bản trong thư mục
  • Sử dụng cho vòng lặp để lặp lại tất cả các tệp
  • Trong mỗi lần lặp, xóa một tập tin đơn.

Hãy cho chúng tôi xem một vài ví dụ để hiểu cách sử dụng điều này để xóa các tệp phù hợp với một mẫu cụ thể.

Thí dụ

>>> file_path.is_file()
True
7

Xóa tệp có tên bắt đầu bằng chuỗi cụ thể

>>> file_path.is_file()
True
8

Xóa tệp có tên chứa một chữ cái cụ thể

Chúng ta có thể cung cấp một loạt các ký tự như chuỗi tìm kiếm bằng cách đặt chúng bên trong & NBSP; giá đỡ vuông (

from shutil import rmtree

rmtree(dir_path)
09).square brackets (
from shutil import rmtree

rmtree(dir_path)
09)
.

Ví dụ sau đây sẽ chỉ ra cách xóa các tệp có tên chứa các ký tự giữa A-G.

>>> file_path.is_file()
True
9

Xóa các tệp khớp với một mẫu từ tất cả các thư mục con

Mặc dù hàm glob () tìm thấy các tệp bên trong một thư mục, có thể tìm kiếm các tệp bên trong các thư mục con bằng hàm

from shutil import rmtree

rmtree(dir_path)
12 tương tự như hàm glob ().

Hàm

from shutil import rmtree

rmtree(dir_path)
12 trả về các tùy chọn Iterator với danh sách các tệp phù hợp với một mẫu bên trong thư mục và thư mục con của nó.

Chúng ta cần đặt cờ đệ quy thành True khi chúng ta tìm kiếm các tệp trong các thư mục con. Sau tên thư mục gốc, chúng ta cần vượt qua

from shutil import rmtree

rmtree(dir_path)
14 để tìm kiếm bên trong các thư mục con.recursive flag to True when we search for the files in subdirectories. After the root folder name, we need to pass
from shutil import rmtree

rmtree(dir_path)
14 for searching inside the subdirectories.

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

Đầu ra

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

Nhận thông báo ngoại lệ thích hợp trong khi xóa thư mục không trống

Để có được thông báo ngoại lệ thích hợp, chúng tôi có thể xử lý nó trong một hàm riêng mà chúng tôi có thể truyền trong tham số

from shutil import rmtree

rmtree(dir_path)
03 hoặc bằng cách bắt nó trong khối Excet Try-Except.

Mã cuối cùng: Để xóa tệp hoặc thư mục: –

  • >>> file_path.is_file()
    True
    
    5
  • Xóa các tệp khớp với một mẫu

Ví dụ: bạn muốn xóa các tệp nếu tên chứa một chuỗi cụ thể.

  • Mô -đun Glob Python, một phần của thư viện tiêu chuẩn Python, được sử dụng để & nbsp; tìm các tệp và thư mục có tên theo một mẫu cụ thể.
  • Phương thức
    from shutil import rmtree
    
    rmtree(dir_path)
    
    04 trả về danh sách các tệp hoặc thư mục phù hợp với mẫu được chỉ định trong đối số
    from shutil import rmtree
    
    rmtree(dir_path)
    
    05.

Hàm này có hai đối số, cụ thể là tên đường dẫn và cờ đệ quy (nếu được đặt thành & nbsp;