How to write multiple lines in text file using Python?

PythonServer Side ProgrammingProgramming

You can use write function to write multiple lines by separating lines by '\n'.

For example

line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
    out.write('{}\n{}\n{}\n'.format(line1,line2,line3))

Alternatively, you can use writelines function to write these lines.

For example

line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
    out.writelines([line1, line2, line3])
raja
Published on 22-Dec-2017 12:06:43
Advertisements