Wednesday, March 12, 2025

[Python] Lesson 33 – Delete a file

-

Delete a file trong Python là quá trình xóa một file hoặc thư mục khỏi hệ thống file của máy tính bằng mã Python. Điều này có thể được thực hiện bằng cách sử dụng module os hoặc os.path.

Ví dụ 1: Xóa một file

import os

if os.path.exists("example.txt"):
  os.remove("example.txt")
  print("File 'example.txt' đã bị xóa thành công!")
else:
  print("Không tìm thấy file 'example.txt'")

Ví dụ 2: Xóa thư mục con trong thư mục hiện tại

import shutil

if os.path.exists("example_folder"):
  shutil.rmtree("example_folder")
  print("Thư mục 'example_folder' đã bị xóa thành công!")
else:
  print("Không tìm thấy thư mục 'example_folder'")

Ví dụ 3: Xóa nhiều file cùng lúc

import os

file_list = ['example1.txt', 'example2.txt', 'example3.txt']

for file_name in file_list:
  if os.path.exists(file_name):
    os.remove(file_name)
    print(f"Tệp tin '{file_name}' đã bị xóa thành công!")
  else:
    print(f"Không tìm thấy file '{file_name}'")

Trong ví dụ này, chúng ta tạo một danh sách các file và sử dụng vòng lặp for để duyệt qua danh sách đó, sau đó sử dụng hàm os.path.exists() để kiểm tra xem file có tồn tại hay không. Nếu file tồn tại, chúng ta sử dụng hàm os.remove() để xóa file đó. Nếu file không tồn tại, chúng ta sẽ in ra một thông báo lỗi.

Một ví dụ thực tế của việc sử dụng delete a file trong Python trên môi trường Linux có thể là xóa một file log khi đã hoàn thành việc xử lý nó. Ví dụ:

import os

def process_log_file(log_file_path):
    # xử lý file nhật ký ở đây

    # xóa file log sau khi xử lý
    os.remove(log_file_path)

Trong ví dụ này, hàm process_log_file sẽ xử lý file nhật ký được chỉ định bởi log_file_path. Sau khi đã hoàn thành xử lý, file log được xóa bằng cách sử dụng hàm os.remove.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

4,956FansLike
256FollowersFollow
223SubscribersSubscribe
spot_img

Related Stories