簡體   English   中英

Python,編寫多行

[英]Python, Writing Multiple Lines

很抱歉,如果這個問題遇到了一個新手,但是我已經找了一段時間,卻找不到任何東西。

我正在測試如何根據請求將多行寫入新行上的txt文件。 我似乎無法將其寫入換行符。 這就是我目前所擁有的。

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

非常感謝,

只需在每行之后添加\\n 例如:

f2.write(title + '\n')
f2.write(des + '\n')
f2.write(tag + '\n')
...
with open('xyz.txt', 'w') as fp:
    fp.writelines([ each_line + '\n' for each_line in ['line_1','line_2','line_3']])

writelines()不會添加換行符'\\n'

writelines(...)
writelines(sequence_of_strings) -> None.  Write the strings to the file.

請注意,未添加換行符。 該序列可以是產生字符串的任何可迭代對象。 這等效於為每個字符串調用write()

line_1
line_2
line_3

因此,您可能需要執行以下操作:

情況1:

tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.writelines([str(data) + '\n' for data in [title,des,img,tag,tag2,tag3]])
f2.close()

情況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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM