How to open a file to write in Python?


To open files in just write mode, specify 'w' as the mode. For example,

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

Above code opens my_file.txt in write mode and rewrites the file to contain "Hello World". A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:

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

Advertisements