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

Cách mở file để ghi trong Python?


Mở file write mode, chỉ định 'w' làm mode.

f = open('my_file.txt', 'w')
f.write('Hello World')
f.close()

Mở my_file.txt write mode, ghi đè nội dung "Hello World". Cách an toàn with open:

with open('my_file.txt', 'w') as f:
    f.write('Hello World')