Reputation: 1607
Sorry if this question comes across a little newbie but iv'e been looking for a while and cannot find anything on this.
I am testing how to Write Multiple Lines to a txt file on a new line per request. I can't seem to get it to write to a newline. This is what I have currently.
import __builtin__
title=('1.0')
des=('1.1')
img=('1.2')
tag=('1.3')
tag2=('1.4')
tag3=('1.5')
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([title,des,img,tag,tag2,tag3])
f2.close()
title=('2.0')
des=('2.1')
img=('2.2')
tag=('2.3')
tag2=('2.4')
tag3=('2.5')
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([title,des,img,tag,tag2,tag3])
f2.close()
title=('3.0')
des=('3.1')
img=('3.2')
tag=('3.3')
tag2=('3.4')
tag3=('3.5')
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([title,des,img,tag,tag2,tag3])
f2.close()
Thanks a lot,
Upvotes: 2
Views: 559
Reputation: 5275
with open('xyz.txt', 'w') as fp:
fp.writelines([ each_line + '\n' for each_line in ['line_1','line_2','line_3']])
writelines()
does not append a newline '\n'
while writing.
writelines(...)
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write()
for each string.
line_1
line_2
line_3
So you might have to do something like this:
Case 1:
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([str(data) + '\n' for data in [title,des,img,tag,tag2,tag3]])
f2.close()
Case 2:
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.write(', '.join([str(data) for data in [title,des,img,tag,tag2,tag3]]) + '\n')
f2.close()
Upvotes: 0
Reputation: 12990
Just add \n
after every line. For example:
f2.write(title + '\n')
f2.write(des + '\n')
f2.write(tag + '\n')
...
Upvotes: 1