繁体   English   中英

如何在 python 中写入文件而不在特定位置添加新行?

[英]How to write to a file in python without adding a new line except at certain place?

我想写入文件而不在 for 循环的迭代中添加新行,除了最后一个。

代码:

items = ['1','2','3']
with open('file.txt', "w") as f:
        f.write('test' + '\n')
        for t in items:
         f.write(t + '\n')
        f.write('test' + '\n')
        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

谢谢。

items = ['1','2','3']
with open('file.txt', "w") as f:
        f.write('test' + '\n')
        for t in items:
         f.write(t)
        f.write('\n'+'test' + '\n')
        for t in items:
         f.write(t)
        f.write('\n'+'end')

这是应该解决您的问题的代码

items = ['1', '2', '3']
with open('file.txt', 'w') as f:
    f.write('test \n')
    for i in items:
        f.write(i)
    f.write('\n')
    f.write('test \n')
    for i in items:
        f.write(i)
    f.write('\n')
    f.write('end')

请注意,您只想遍历 for 循环中的列表项,然后在下一个“测试”之前为新行添加一个单独的写入语句 此外,最好只在单引号内使用转义字符 \n 作为换行符用'+'符号附加它。

如果您希望列表成为字符串,请遵循此模板

数字 = ['1', '2', '3'] str1 = ""

for i in num: str1 += i

打印(str1)

输出:123

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM