Hướng dẫn how to delete a text file in python - cách xóa một tệp văn bản trong python


Xóa một tập tin

Để xóa một tệp, bạn phải nhập mô -đun HĐH và chạy chức năng

from shutil import rmtree

rmtree(dir_path)
8 của nó:

Thí dụ

Xóa tệp "demofile.txt":

Nhập Osos.Remove ("demofile.txt")
os.remove("demofile.txt")


Kiểm tra xem tệp có tồn tại không:

Để tránh bị lỗi, bạn có thể muốn kiểm tra xem tệp có tồn tại trước khi bạn cố gắng xóa nó không:

Thí dụ

Xóa tệp "demofile.txt":

Nhập Osos.Remove ("demofile.txt")
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")


Kiểm tra xem tệp có tồn tại không:

Để tránh bị lỗi, bạn có thể muốn kiểm tra xem tệp có tồn tại trước khi bạn cố gắng xóa nó không:

Thí dụ

Xóa tệp "demofile.txt":

Nhập Osos.Remove ("demofile.txt")
os.rmdir("myfolder")

Kiểm tra xem tệp có tồn tại không: You can only remove empty folders.



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

Để 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()
5 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()
2.

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()
7 để 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ư
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()
8 hoặc sử dụng các chuỗi thô, như
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) :

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

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()
1 thất bại 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
2

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()
2 (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
4 hoặc
>>> file_path.is_file()
True
5

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

from shutil import rmtree

rmtree(dir_path)
7

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

>>> file_path.is_file()
True
7 - 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.

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

Sử dụng tệp ...
File = Open ("Sample.txt", "R+").
tập tin. cắt ngắn (0).
tập tin. gần().

Làm cách nào để xóa một tệp trong Python 3?

Xóa () Phương thức trong Python có thể được sử dụng để xóa các tệp và HĐH.Phương thức rmdir () có thể được sử dụng để xóa một thư mục trống.Shutil.Phương thức rmtree () có thể được sử dụng để xóa một thư mục cùng với tất cả các tệp của nó., and the os. rmdir() method can be used to delete an empty folder. The shutil. rmtree() method can be used to delete a folder along with all of its files.

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

Điều này có thể được thực hiện bằng các cách sau: Mở tệp ở chế độ đọc, lấy tất cả dữ liệu từ tệp.Hạ lại tệp một lần nữa ở chế độ ghi và ghi lại tất cả dữ liệu, ngoại trừ dữ liệu sẽ bị xóa.Viết lại tệp trong một tệp mới ngoại trừ dữ liệu chúng tôi muốn xóa.

Làm cách nào để xóa một tệp văn bản khỏi thư mục trong Python?

Cách xóa một tập tin trong Python..
Tìm đường dẫn của một tập tin.Chúng ta có thể xóa một tệp bằng cả đường dẫn tương đối và đường dẫn tuyệt đối.....
Sử dụng hàm os.remove () để xóa tệp.Mô -đun HĐH trong Python cung cấp các phương pháp để tương tác với hệ điều hành trong Python.....
Sử dụng hàm rmtree () của mô -đun SHOTIL để xóa thư mục ..