# How to write a single line in text file using Python?

PythonServer Side ProgrammingProgramming

You can simply write the line to file using write function.

### For example

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

Alternatively, you can use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

For Python 3 you don't need the import, since the  print() function is the default.

Published on 22-Dec-2017 16:34:41