Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách mở file chỉ đọc trong Python?


Mở file read mode, chỉ định 'r' làm mode.

f = open('my_file.txt', 'r')
file_content = f.read()
f.close()

Mở my_file.txt read mode, lưu nội dung vào file_content. Cách an toàn hơn with open:

with open('my_file.txt', 'r') as f:
    print(f.read())