Hướng dẫn how to delete folder in python - cách xóa thư mục 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 "", 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

>>> 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ụ: Xóa một thư mục trống bằng rmdir ()

Trong ví dụ này, chúng tôi sẽ xóa một thư mục trống, chúng tôi chỉ cần chỉ định tên thư mục nếu nó nằm trong thư mục gốc

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

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

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 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()
08
>>> 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()
10
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()
11

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

>>> 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 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()
17
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
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()
19

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

Output:  

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

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

Xóa một tập tin hoặc thư mục trong Python.

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

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

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

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

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

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

Output:

from shutil import rmtree

rmtree(dir_path)
8

Ví dụ 3: Kiểm tra xem tệp có tồn tại trước khi xóa không Check if File Exists Before Deleting

Xử lý lỗi trong khi sử dụng phương thức os.Remove ().

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
8
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
8

>>> 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.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
file_path.parent.mkdir()
file_path.touch()
6
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
1
file_path.parent.mkdir()
file_path.touch()
8

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

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 "", 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'
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 "", 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'
7
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
2

Output:

from shutil import rmtree

rmtree(dir_path)
9

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

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

Phương thức OS.RMDIR () trong Python được sử dụng để xóa hoặc xóa một thư mục trống. Oserror sẽ được nâng lên nếu đường dẫn được chỉ định không phải là một thư mục trống.OSError will be raised if the specified path is not an empty directory.

Cú pháp của OS.RMDIR ()

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

Parameter:  

  • Đườ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. 
  • 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 tất cả các thư mục khỏi thư mục Delete all directories from a Directory

Giả sử các thư mục là - & nbsp;

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

Chúng tôi muốn loại bỏ các chuyên viên viên 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
>>> 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)
03

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

from shutil import rmtree

rmtree(dir_path)
10

Output:  

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

Ví dụ 2: Xử lý lỗi trong khi xóa thư mục

Xử lý lỗi trong khi sử dụng phương thức os.rmdir (), & 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

Ví dụ 2: Xử lý lỗi trong khi xóa thư mục

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

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 "", 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'
3

Lưu ý: Để biết thêm về Os.Remove () Bấm vào đây.

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

Xóa tệp/Dir bằng phương thức OS.RMDIR () To know more about os.rmdir() click here.

Phương thức OS.RMDIR () trong Python được sử dụng để xóa hoặc xóa một thư mục trống. Oserror sẽ được nâng lên nếu đường dẫn được chỉ định không phải là một thư mục trống.

Cú pháp của OS.RMDIR ()

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

Đườ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; 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. 
  • 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; If ignore_errors is true, errors resulting from failed removals will be 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; If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

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

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

Giả sử các thư mục là - & nbsp;

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

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

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)
03# Directory inside parent directory: 

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

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
 

Hướng dẫn how to delete folder in python - cách xóa thư mục trong python

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

Ví dụ 2: Xử lý lỗi trong khi xóa thư mục

Python3

Xử lý lỗi trong khi sử dụng phương thức os.rmdir (), & nbsp;

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

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.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 to delete folder in python - cách xóa thư mục trong python

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

Ví dụ 3: Kiểm tra xem tệp có tồn tại trước khi xóa không

Python3

Xử lý lỗi trong khi sử dụng phương thức os.rmdir (), & nbsp;

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

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

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

Ví dụ 3: Kiểm tra xem tệp có tồn tại trước khi xóa không

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

  • Chức năng - Chức năng nâng cao ngoại lệ.function which raised the exception.
  • Đường dẫn - tên đường dẫn được truyền đi trong khi loại bỏ path name passed which raised the exception while removal
  • ExcInfo - Thông tin ngoại lệ được nêu bởi sys.exc_info () exception info raised by sys.exc_info()

Dưới đây là triển khai & 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

from shutil import rmtree

rmtree(dir_path)
82
from shutil import rmtree

rmtree(dir_path)
83

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:

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

Cú pháp của pathlib.path

Cú pháp: pathlib.path (trống_dir_path) .rmdir ()

Parameter:  

  • trống_dir_path: một đối tượng giống như đường dẫn đại diện cho một đường dẫn thư mục trống. 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 empty directory path. A path-like object is either a string or bytes object representing a path. 

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ụ: Xóa một thư mục trống bằng rmdir ()

Trong ví dụ này, chúng tôi sẽ xóa một thư mục trống, chúng tôi chỉ cần chỉ định tên thư mục nếu nó nằm trong thư mục gốc

Python3

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

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()
08
>>> 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()
10
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()
11

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

>>> 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 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()
17
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
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()
19

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 thế nào để bạn xóa một tệp hoặc thư mục trong Python?

Xóa một tập tin hoặc thư mục trong Python..
hệ điều hành. Xóa () Xóa một tệp ..
hệ điều hành. Hủy liên kết () xóa một tệp. nó là một tên UNIX của phương thức Remove () ..
giao thoa. rmtree () xóa một thư mục và tất cả các nội dung của nó ..
Pathlib. Đường dẫn. Hẹn phát hành () Xóa một tệp Một mô -đun pathlib có sẵn trong Python 3.4 trở lên ..

Làm cách nào để xóa một thư mục đầy đủ 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.

Làm cách nào để xóa một 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.

Làm thế nào để bạn xóa một tệp trong Python?

Sử dụng mô -đun OS trong Python để sử dụng mô -đun OS để xóa tệp, chúng tôi nhập nó, sau đó sử dụng hàm Remove () do mô -đun cung cấp để xóa tệp.Nó lấy đường dẫn tệp làm tham số.Bạn không thể chỉ xóa một tệp mà còn là một thư mục sử dụng mô -đun HĐH.import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter. You can not just delete a file but also a directory using the os module.