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[]
7Hã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]
0Và chúng ta có thể thấy toàn bộ sự việc đã bị xóa:
from shutil import rmtree
rmtree[dir_path]
1Python 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]
2Và sau đó bạn có thể bí danh thư viện thành
>>> file_path.is_file[]
True
4from shutil import rmtree
rmtree[dir_path]
3Hoặ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]
4Nế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
7from shutil import rmtree
rmtree[dir_path]
5hoặc
from shutil import rmtree
rmtree[dir_path]
6Và 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]
7Lư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
>>> file_path.unlink[] # remove file
>>> file_path.is_file[]
False
>>> file_path.exists[]
False
0 >>> file_path.is_file[]
True
4Python3
>>> 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
1from 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[]
10from 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
9from 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[]
3Output:
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[]
2Output:
from shutil import rmtree
rmtree[dir_path]
8Ví 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
9file_path.parent.mkdir[]
file_path.touch[]
0file_path.parent.mkdir[]
file_path.touch[]
1>>> [directory_path / 'foo.my'].touch[]
>>> [directory_path / 'bar.my'].touch[]
3file_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
9file_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[]
8file_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'
0file_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'
3file_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[]
2Output:
from shutil import rmtree
rmtree[dir_path]
9Lư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;
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
1from 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]
03from 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]
09from shutil import rmtree
rmtree[dir_path]
10
Output:
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
1from 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]
15from 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
9file_path.parent.mkdir[]
file_path.touch[]
0
file_path.parent.mkdir[]
file_path.touch[]
1from shutil import rmtree
rmtree[dir_path]
10Ví 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'
0file_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'
3Lư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[]
0Xó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:
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:
04from shutil import rmtree
rmtree[dir_path]
3 >>> file_path.unlink[] # remove file
>>> file_path.is_file[]
False
>>> file_path.exists[]
False
06 from shutil import rmtree
rmtree[dir_path]
8>>> 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
09from shutil import rmtree
rmtree[dir_path]
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
1from 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]
15file_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
9from 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[]
2from shutil import rmtree
rmtree[dir_path]
58Output:
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>>> 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 >>> directory_path.rmdir[] # remove directory
>>> directory_path.is_dir[]
False
>>> directory_path.exists[]
False
1 >>> directory_path.rmdir[] # remove directory
>>> directory_path.is_dir[]
False
>>> directory_path.exists[]
False
6>>> [directory_path / 'foo.my'].touch[]
>>> [directory_path / 'bar.my'].touch[]
2>>> [directory_path / 'foo.my'].touch[]
>>> [directory_path / 'bar.my'].touch[]
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
1from 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]
15file_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
9from 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[]
2from shutil import rmtree
rmtree[dir_path]
74>>> file_path.unlink[] # remove file
>>> file_path.is_file[]
False
>>> file_path.exists[]
False
3from shutil import rmtree
rmtree[dir_path]
76>>> [directory_path / 'foo.my'].touch[]
>>> [directory_path / 'bar.my'].touch[]
2Output:
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>>> 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>>> directory_path.rmdir[] # remove directory >>> directory_path.is_dir[] False >>> directory_path.exists[] False
1>>> directory_path.rmdir[] # remove directory >>> directory_path.is_dir[] False >>> directory_path.exists[] False
6>>> [directory_path / 'foo.my'].touch[] >>> [directory_path / 'bar.my'].touch[]
2>>> [directory_path / 'foo.my'].touch[] >>> [directory_path / 'bar.my'].touch[]
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
1from shutil import rmtree
rmtree[dir_path]
82 from shutil import rmtree
rmtree[dir_path]
83file_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
9from shutil import rmtree
rmtree[dir_path]
87>>> [directory_path / 'foo.my'].touch[]
>>> [directory_path / 'bar.my'].touch[]
2file_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
8from 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[]
2from 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
3from 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[]
05Output:
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
4from 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[]
10from 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
9from 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[]
19Output:
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