Bài viết thảo luận các method xử lý file Python. Các ví dụ code minh họa tạo, đọc, ghi, xóa file.
Tạo file trong Python
Dùng method open() với 2 tham số: tên file và mode: 'x', 'a', 'w'.
'x': tạo file mới. Ném lỗi nếu file đã tồn tại.'a': append (ghi thêm). Tạo file nếu chưa tồn tại.'w': write (ghi đè). Tạo file nếu chưa tồn tại.
file = open("somefile.txt", "x")
File somefile.txt được tạo mới.
Đọc file trong Python
Dùng open() với mode 'r' (read).
Ví dụ đọc file somefile.txt có nội dung:
Hello!! Welcome to Python
Goodbye.
file = open('somefile.txt', 'r')
print(file.read())
file.close()
Kết quả in ra toàn bộ nội dung.
Đọc một phần file
Truyền số ký tự vào read():
file = open('somefile.txt', 'r')
print(file.read(5)) # 'Hello'
file.close()
Đọc file theo dòng (Line by line)
Dùng readline() đọc từng dòng.
Chỉ đọc một dòng
file = open('somefile.txt', 'r')
print(file.readline())
file.close()
Kết quả: Hello!!
Đọc hai dòng
file = open('somefile.txt', 'r')
print(file.readline())
print(file.readline())
file.close()
Kết quả: Hello!! Welcome to Python
Đọc tất cả dòng
Dùng for loop:
file = open('somefile.txt', 'r')
for x in file:
print(x)
# Output:
# Hello!!
# Welcome to Python
# Goodbye
Ghi file trong Python
Dùng open() với mode 'a' (append) hoặc 'w' (write/overwrite). Cả hai đều tạo file nếu chưa tồn tại.
Ghi file mới
file = open('writefile.txt', 'w')
file.write("Write some content!")
file.close()
File writefile.txt được tạo với nội dung: Write some content!
Lưu ý: Mode 'w' sẽ ghi đè nội dung nếu file đã tồn tại!
Append nội dung vào file có sẵn
file = open('writefile.txt', 'a')
file.write("\nWrite more content!")
file.close()
Nội dung file writefile.txt:
Write some content! Write more content!
Xóa file trong Python
Import module os và dùng remove():
import os
if os.path.exists("writefile.txt"):
os.remove("writefile.txt")
Method kiểm tra file tồn tại trước khi xóa. Ném lỗi nếu file không tồn tại.