File text chứa văn bản thuần túy. Python có hàm built-in đọc, tạo, ghi file text. Có 3 cách đọc:
- read() – đọc toàn file, trả về chuỗi đơn.
- readline() – đọc một dòng, trả về chuỗi.
- readlines() – đọc tất cả dòng, trả về list chuỗi.
Đọc file trong Python
Mở file myfile.txt chế độ đọc "r" bằng open().
Ví dụ
file = open("myfile.txt", "r")
print("read function: ")
print(file.read())
print()
file.seek(0) # đưa con trỏ về đầu file
print("readline function:")
print(file.readline())
print()
file.seek(0)
print("readlines function:")
print(file.readlines())
file.close()
Kết quả
read function: This is an article on reading text files in Python. Python has inbuilt functions to read a text file. We can read files in three different ways. Create a text file which you will read later. readline function: This is an article on reading text files in Python. readlines function: ['This is an article on reading text files in Python.\n', 'Python has inbuilt functions to read a text file.\n', 'We can read files in three different ways.\n', 'Create a text file which you will read later.']
Nhận thấy: read() đọc cả file, readline() đọc 1 dòng, readlines() trả list các dòng.