How to open a file to write in Python?

PythonServer Side ProgrammingProgramming

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

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

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')
Published on 22-Dec-2017 06:30:53