1. Giới thiệu
Ta hay thường gặp các bài toán duyệt danh sách các file trong một thư mục cho trước, xử lý với file. Nó được sử dụng nhiều trong các bài toán machine learning. Giả sử bạn muốn load toàn bộ file ảnh vào chương trình để tiến hành làm một việc gì đó.
2.Các hàm xử lý
a. Mở file
Đọc và ghi file rất đơn giản để làm được điều này, bạn phải mở file ở chế độ thích hợp.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mở file ở chế độ đọc | |
with open('data.txt', 'r') as f: | |
data = f.read() | |
# Mở file ở chế độ ghi | |
with open('data.txt', 'w') as f: | |
data = 'data write to file' | |
f.write(data) |
b. Xóa file, thư mục
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
# Xóa file | |
os.remove(file_path) | |
# Xóa thư mục | |
os.rmdir(folder_path) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
# Đường dẫn tới thư mục chứa file | |
base_path = 'demo' | |
print(os.listdir(base_path)) # ['file_1.jpeg', 'file_2.jpg', 'file_3.jpg', 'file_5.jpg'] là tất cả file trong thư mục demo |
d. Liệt kê file theo pattern
Sử dụng glob cho phép liệt kê file và thư mục theo một pattern nào đó. Hay nói cách khác là tìm kiếm các file thỏa mãn quy tắc cho trước.
e. Sao chép, di chuyển, thay đổi tên file và thư mục
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shutil | |
# sao chép file | |
shutil.copy(source, destination) | |
# sao chép thư mục | |
shutil.copytree(source, destination) | |
# di chuyển file, thư mục | |
shutil.move(source, destination) | |
# thay đổi tên | |
os.rename(old, new) | |
Trên đây chỉ là một số những ứng dụng cơ bản của file. Còn rất nhiều nữa mà mình không thể trình bày tất cả trong một bài viết được. Các bạn có thể tham khảo link tại đây để biết thêm chi tiết
0 nhận xét:
Đăng nhận xét