【发布时间】:2022-08-08 09:10:44
【问题描述】:
我想写入文件而不在 for 循环的迭代中添加新行,除了最后一个。
代码:
items = [\'1\',\'2\',\'3\']
with open(\'file.txt\', \"w\") as f:
f.write(\'test\' + \'\\n\')
for t in items:
f.write(t + \'\\n\')#i didnt know i could add the \'\\n\'
f.write(\'test\' + \'\\n\')#here for it to work
for t in items:
f.write(t + \'\\n\')
f.write(\'end\')
文件中的输出:
test
1
2
3
test
1
2
3
end
我想要在文件中的输出:
test
123
test
123
end
我是 python 新手,对于任何反复无常感到抱歉。
-
\"我想在不添加新行的情况下写入文件\": 那你为什么要在
f.write(t + \'\\n\')中添加换行符?不要在循环中添加任何内容,然后在开始下一行之前写一个换行符。 -
...并在参数的开头添加 \'\\n\' 到第二个 f.write(\'test\' + \'\\n\') 和 f.write(\'end\' )
标签: python file-writing