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

Cách ghi nhiều dòng vào file text bằng Python?


Dùng hàm write ghi nhiều dòng tách bằng '\n'.

Ví dụ

line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt', 'w') as out:
    out.write('{}\n{}\n{}\n'.format(line1, line2, line3))

Thay thế, dùng writelines ghi các dòng:

Ví dụ

line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt', 'w') as out:
    out.writelines([line1, line2, line3])