Dưới đây là các ví dụ cơ bản về cách thao tác với file và thư mục.
# Mở file để đọc
with open("example.txt", "r") as file:
content = file.read()
print(content)
"r": Mở file ở chế độ đọc.
with open() là cách tốt để đảm bảo file được đóng tự động sau khi hoàn thành.
# Mở file để ghi
with open("example.txt", "w") as file:
file.write("Hello, Python!")
"w": Mở file ở chế độ ghi. Nếu file không tồn tại, nó sẽ được tạo mới.
# Mở file để thêm dữ liệu vào cuối file
with open("example.txt", "a") as file:
file.write("\nAppended text.")
"a": Mở file ở chế độ append, tức là thêm dữ liệu vào cuối file mà không làm mất dữ liệu cũ.
# Đọc từng dòng trong file
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() để loại bỏ dấu newline
import os
# Kiểm tra thư mục có tồn tại không
if not os.path.exists("my_folder"):
os.mkdir("my_folder") # Tạo thư mục nếu không tồn tại
print("Thư mục đã được tạo!")
else:
print("Thư mục đã tồn tại.")
import os
# Liệt kê các file và thư mục trong thư mục
files_and_dirs = os.listdir("my_folder")
print(files_and_dirs)
import os
# Xoá thư mục rỗng
if os.path.exists("my_folder"):
os.rmdir("my_folder") # Xoá thư mục rỗng
print("Thư mục đã bị xoá.")
else:
print("Thư mục không tồn tại.")
shutil là thư viện mạnh mẽ để sao chép, di chuyển, xóa file và thư mục.
import shutil
# Sao chép file
shutil.copy("example.txt", "copy_example.txt")
print("File đã được sao chép.")
import shutil
# Di chuyển file
shutil.move("example.txt", "my_folder/example.txt")
print("File đã được di chuyển.")
import os
# Xoá file
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File đã bị xoá.")
else:
print("File không tồn tại.")
pathlib là một thư viện hiện đại hơn, cung cấp các cách thức quản lý file và thư mục dễ dàng hơn.
from pathlib import Path
# Tạo đối tượng Path
file_path = Path("example.txt")
# Kiểm tra file tồn tại
if file_path.exists():
print(f"File {file_path} tồn tại.")
else:
print(f"File {file_path} không tồn tại.")
from pathlib import Path
# Tạo thư mục
folder = Path("my_folder")
folder.mkdir(exist_ok=True) # exist_ok=True để tránh lỗi nếu thư mục đã tồn tại
print("Thư mục đã được tạo.")
from pathlib import Path
import shutil
# Di chuyển file
source = Path("example.txt")
destination = Path("my_folder/example.txt")
shutil.move(source, destination)
print(f"File {source} đã được di chuyển đến {destination}.")
# Sao chép file
shutil.copy(source, destination)
print(f"File {source} đã được sao chép đến {destination}.")
Tìm kiếm:
Trong Python, việc quản lý file và thư mục có thể thực hiện rất dễ dàng nhờ vào thư viện os, shutil và pathlib.