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

Cách ghi một dòng vào file text bằng Python?


Ghi dòng vào file dùng hàm write.

Ví dụ

f = open('myfile', 'w')
f.write('hi there\n')  # python chuyển \n thành os.linesep
f.close()  # có thể bỏ qua, destructor sẽ gọi

Thay thế, dùng hàm print() (Python 2.6+):

from __future__ import print_function  # Chỉ cần Python 2
print("hi there", file=f)

Python 3 không cần import, print() mặc định.