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

Cách đọc toàn bộ file text dòng per dòng Python?


Hàm read đọc toàn file. Dùng readlines đọc từng dòng.

Ví dụ

Đọc file line by line:

f = open('my_file.txt', 'r+')
for line in f.readlines():
    print(line)
f.close()

Cũng dùng with...open mở file đọc từng dòng.

Ví dụ

with open('my_file.txt', 'r+') as f:
    for line in f.readlines():
        print(line)

https://www.codespeedy.com/read-a-specific-line-from-a-text-file-in-python/