Computer >> Computer tutorials >  >> Programming >> Python

How to write multiple lines in text file using Python?


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])