Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi 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:

Show
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 do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi 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

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

Làm cách nào để xóa các tệp khỏi thư mục?

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

Output:  

Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi thư mục trong python?

Mở máy tính hoặc Windows Explorer của tôi. Lừa và chọn tệp hoặc thư mục bạn muốn xóa, nhấp vào Tệp trong thanh menu trên cùng và chọn Xóa.

Lệnh nào được sử dụng để xóa các tệp trong Python?

Python3

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

Làm cách nào để xóa các tệp khỏi thư mục?

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

Mở máy tính hoặc Windows Explorer của tôi. Lừa và chọn tệp hoặc thư mục bạn muốn xóa, nhấp vào Tệp trong thanh menu trên cùng và chọn Xóa.

Output:

from shutil import rmtree

rmtree(dir_path)
8

Lệnh nào được sử dụng để xóa các tệp trong Python? Check if File Exists Before Deleting

Trong Python, bạn có thể sử dụng HĐH. Xóa () Phương thức để xóa các tệp và HĐH. Phương thức rmdir () để xóa một thư mục trống. Nếu bạn muốn xóa một thư mục với tất cả các tệp của nó, bạn có thể sử dụng Shutil.

Python3

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

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

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

Làm cách nào để xóa các tệp khỏi thư mục?

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

Mở máy tính hoặc Windows Explorer của tôi. Lừa và chọn tệp hoặc thư mục bạn muốn xóa, nhấp vào Tệp trong thanh menu trên cùng và chọn Xóa.To know more about os.remove() click here.

Lệnh nào được sử dụng để xóa các tệp trong Python?

Trong Python, bạn có thể sử dụng HĐH. Xóa () Phương thức để xóa các tệp và HĐH. Phương thức rmdir () để xóa một thư mục trống. Nếu bạn muốn xóa một thư mục với tất cả các tệp của nó, bạn có thể sử dụng Shutil.OSError will be raised if the specified path is not an empty directory.

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

Xóa tệp văn bản bằng hàm Open () trong chế độ ghi Mở tệp ở chế độ ghi sẽ tự động xóa nội dung của tệp. Hàm Open () có hai đối số, tệp văn bản chúng tôi muốn mở và chế độ chúng tôi đang mở. Mở một tệp trong chế độ ghi xóa dữ liệu của nó.os.rmdir(path, *, dir_fd = None) 

Parameter:  

  • 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; 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 do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi 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 do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi 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)
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

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

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

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

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

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

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
To know more about os.rmdir() click here.

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
>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my
9
from shutil import rmtree

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

rmtree(dir_path)
31

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

Xóa tệp/DIR bằng cách sử dụng Shutil.rmtree () shutil.rmtree(path, ignore_errors=False, onerror=None) 

Parameters:  

  • SOWN.RMTREE () được sử dụng để xóa toàn bộ cây thư mục, đường dẫn phải trỏ đến một thư mục (nhưng không phải là một liên kết tượng trưng đến một thư mục).A path-like object representing a file path. A path-like object is either a string or bytes object representing a path. 
  • Cú pháp của SOWL.RMTREE () If ignore_errors is true, errors resulting from failed removals will be ignored. 
  • Cú pháp: shutil.rmtree (đường dẫn, bỏ qua_errors = false, onerror = none) & nbsp; If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

Đườ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;

bỏ qua_errors: Nếu bỏ qua_errors là đúng, các lỗi do loại bỏ không thành công sẽ bị bỏ qua. & nbsp; 

Onerror: Nếu bỏ qua_error là sai hoặc bị bỏ qua, các lỗi đó được xử lý bằng cách gọi một trình xử lý được chỉ định bởi Onerror.

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

Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi thư mục trong python?

Ví dụ 1: & nbsp;# Directory inside parent directory: 

Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi thư mục trong python?

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

Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi thư mục trong python?

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

& nbsp;# thư mục bên trong thư mục mẹ: & nbsp;

Python3

# Tệp bên trong thư mục phụ: & 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)
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)
58

Output:  

Hướng dẫn how do i remove a file from a directory in python? - làm cách nào để xóa tệp khỏi 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

# Tệp bên trong thư mục phụ: & 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)
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)
74
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from shutil import rmtree

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

Output:

Ví dụ 2: 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;

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
    function which raised the exception.
  • 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
    path name passed which raised the exception while removal
  • file_path.parent.mkdir()
    file_path.touch()
    
    1
    >>> for each_file_path in directory_path.glob('*.my'):
    ...     print(f'removing {each_file_path}')
    ...     each_file_path.unlink()
    ... 
    removing ~/directory/foo.my
    removing ~/directory/bar.my
    
    8
    >>> for each_file_path in directory_path.glob('*.my'):
    ...     print(f'removing {each_file_path}')
    ...     each_file_path.unlink()
    ... 
    removing ~/directory/foo.my
    removing ~/directory/bar.my
    
    9
    from shutil import rmtree
    
    rmtree(dir_path)
    
    40
    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    1
    from shutil import rmtree
    
    rmtree(dir_path)
    
    31
    exception info raised by sys.exc_info()

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

Python3

# Tệp bên trong thư mục phụ: & 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

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

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

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 pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()
03
>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
3
from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()
05

Output:

Ví dụ 2: 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;

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

Parameter:  

  • file_path.parent.mkdir()
    file_path.touch()
    
    1
    >>> for each_file_path in directory_path.glob('*.my'):
    ...     print(f'removing {each_file_path}')
    ...     each_file_path.unlink()
    ... 
    removing ~/directory/foo.my
    removing ~/directory/bar.my
    
    8
    >>> for each_file_path in directory_path.glob('*.my'):
    ...     print(f'removing {each_file_path}')
    ...     each_file_path.unlink()
    ... 
    removing ~/directory/foo.my
    removing ~/directory/bar.my
    
    9
    from shutil import rmtree
    
    rmtree(dir_path)
    
    40
    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    
    1
    from shutil import rmtree
    
    rmtree(dir_path)
    
    31
    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 cách nào để xóa các tệp khỏi thư mục?

Mở máy tính hoặc Windows Explorer của tôi. Lừa và chọn tệp hoặc thư mục bạn muốn xóa, nhấp vào Tệp trong thanh menu trên cùng và chọn Xóa. Locate and select the file or folder you want to delete, click File in the top menu bar, and select Delete.

Lệnh nào được sử dụng để xóa các tệp trong Python?

Trong Python, bạn có thể sử dụng HĐH.Xóa () Phương thức để xóa các tệp và HĐH.Phương thức rmdir () để xóa một thư mục trống.Nếu bạn muốn xóa một thư mục với tất cả các tệp của nó, bạn có thể sử dụng Shutil.

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

Xóa tệp văn bản bằng hàm Open () trong chế độ ghi Mở tệp ở chế độ ghi sẽ tự động xóa nội dung của tệp.Hàm Open () có hai đối số, tệp văn bản chúng tôi muốn mở và chế độ chúng tôi đang mở. Mở một tệp trong chế độ ghi xóa dữ liệu của nó.Using the open() Function in write Mode Opening a file in write mode will automatically delete the file's contents. The open() function takes two arguments, the text file we'd like to open and the mode we're opening it in. Opening a file in write mode clears its data.