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

Trong hướng dẫn này, chúng ta sẽ học cách xóa một tệp hoặc thư mục trong


 Enter filename:- sample.txt
 File not found in the directory
0. Quá trình xóa tệp hoặc thư mục trong Python rất đơn giản bằng cách sử dụng mô-đun

 Enter filename:- sample.txt
 File not found in the directory
1

  • 
     Enter filename:- sample.txt
     File not found in the directory
    
    2 – Xóa một tập tin
  • 
     Enter filename:- sample.txt
     File not found in the directory
    
    3 – Xóa một thư mục
  • 
     Enter filename:- sample.txt
     File not found in the directory
    
    0 – Xóa một thư mục và tất cả nội dung của nó

1. Xóa một tập tin

Đầu tiên, chúng ta sẽ thấy một phương pháp xóa tệp khỏi thư mục bằng cách sử dụng


 Enter filename:- sample.txt
 File not found in the directory
2


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")

đầu ra


 Enter filename:- sample.txt
 File not found in the directory

2. Xóa một thư mục

Thư mục mà chúng ta sẽ xóa phải trống. Python sẽ hiển thị Cảnh báo cho biết thư mục không trống. Trước khi xóa một thư mục, hãy đảm bảo rằng thư mục đó trống. Chúng tôi có thể lấy danh sách các tệp có trong thư mục bằng Phương thức


 Enter filename:- sample.txt
 File not found in the directory
2. Từ đó, chúng ta có thể kiểm tra xem thư mục có trống hay không


#!/usr/bin/python
import os

# getting the folder path from the user
folder_path = input("Enter folder path:- ")

# checking whether folder exists or not
if os.path.exists(folder_path):

    # checking whether the folder is empty or not
    if len(os.listdir(folder_path)) == 0:
        # removing the file using the os.remove() method
        os.rmdir(folder_path)
    else:
        # messaging saying folder not empty
        print("Folder is not empty")
else:
    # file not found message
    print("File not found in the directory")

đầu ra


Enter folder path:- sample
Folder is not empty

3. Xóa một thư mục và tất cả nội dung của nó


#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= input("Enter directory name: ")

try:
    shutil.rmtree(mydir)
except OSError as e:
    print("Error: %s - %s." % (e.filename, e.strerror))

đầu ra


Enter directory name: d:\logs
Error: d:\logs - The system cannot find the path specified.

Người giới thiệu

Hafeezul Kareem

Tôi là một Pythoneer hiện đang học năm thứ 3 trong khóa học Khoa học máy tính của tôi. Tôi sẽ tốt nghiệp khoa học máy tính trong 2 năm nữa. Tôi rất thích Python và lập trình. Tôi thích tìm hiểu các công nghệ mới và nhiệt tình chia sẻ kiến ​​thức của mình với cộng đồng lập trình

Mô-đun hệ điều hành trong Python cung cấp các chức năng để tương tác với hệ điều hành. Mô-đun tiện ích tiêu chuẩn này cung cấp một cách di động để sử dụng chức năng phụ thuộc vào hệ điều hành. Mô-đun này có thể xóa tệp hoặc đường dẫn tệp nhưng không thể xóa thư mục. Nếu đường dẫn được chỉ định là một thư mục, thì mô-đun sẽ tăng OSError

cú pháp

________số 8

Trường hợp 1. Để loại bỏ một tập tin

Đầu vào

import os

file = 'file.txt'  
location = "/home/User/Documents"
path = os.path.join(location, file)  
os.remove(path)

print (“The file has been removed")

đầu ra


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
0

Trong đoạn mã trên, trước tiên chúng tôi chỉ định tệp nào chúng tôi muốn xóa và vị trí của tệp đó. Sau đó, sau khi tham gia, chúng tôi sử dụng hệ điều hành. thao tác remove() để xóa nó

trường hợp 2. Đường dẫn được chỉ định là một thư mục

Đầu vào


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
1

đầu ra


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
2

Ở đây, chúng tôi không cần sử dụng thao tác 'tham gia' vì chúng tôi trực tiếp chỉ định vị trí chính xác. Đảm bảo nhập thư viện hệ điều hành trước khi sử dụng hệ điều hành. loại bỏ() chức năng





Sử dụng mô-đun pathlib để xóa tệp trong Python

Mô-đun pathlib rất hữu ích trong việc xóa hoặc xóa tệp trong Python 3. 4 trở lên. Nó tương tự như hệ điều hành. remove() và phải tạo một đối tượng đường dẫn lúc đầu

Đầu vào


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
3

Khi một thể hiện của lớp Path được tạo, WindowsPath hoặc PosixPath sẽ được trả về tùy theo máy bạn đang làm việc. Và hàm unlink() được sử dụng để xóa tệp hoặc liên kết tượng trưng


Xóa thư mục trống

Không thể sử dụng hai cách tiếp cận trên để xóa thư mục. hệ điều hành. Hàm rmdir() trong mô-đun hệ điều hành có thể xóa một thư mục trống trong Python

Đầu vào


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
4

đầu ra


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
5

hệ điều hành. Hàm rmdir() chỉ có thể được sử dụng để xóa một thư mục trống. Nếu bạn chỉ định một thư mục chứa tệp, lỗi sau sẽ được trả về

Đầu vào


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
6

đầu ra


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")
7

Xóa thư mục không trống

Bạn có thể sử dụng mô-đun thao tác tệp cấp cao, Shutil để xóa tệp hoặc bộ sưu tập tệp. Bạn có thể sử dụng mô-đun này theo cách tương tự như mô-đun os. rmdir() nhưng tại đây bạn cũng có thể xóa các thư mục không trống. Tất cả nội dung bên trong thư mục cũng bị xóa

Đầu vào

import os

file = 'file.txt'  
location = "/home/User/Documents"
path = os.path.join(location, file)  
os.remove(path)

print (“The file has been removed")
0

đầu ra

import os

file = 'file.txt'  
location = "/home/User/Documents"
path = os.path.join(location, file)  
os.remove(path)

print (“The file has been removed")
1

Chỉ cần nhớ rằng bạn không thể xóa một tệp duy nhất bằng Shutil. hàm rmtree(). Để xóa một tệp, bạn có thể sử dụng lệnh os. remove() và mô-đun pathlib đã được minh họa ở trên


Bớt tư tưởng

Trong Python, xóa tệp là một thao tác rất phổ biến. hệ điều hành. remove() và mô-đun pathlib có thể xóa một tệp. Trong khi hệ điều hành. Hàm rmdir() xóa thư mục trống và mô-đun Shutil xóa thư mục không trống trong Python. Bạn có thể tìm hiểu các khái niệm Python khác tại đây