简体   繁体   English

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

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

I want to write to a file without adding a new line at the iterations of a for loop except the last one.我想写入文件而不在 for 循环的迭代中添加新行,除了最后一个。

Code:代码:

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

Output in the file:文件中的输出:

test
1
2
3
test
1
2
3
end

Output I want in the file:我想要在文件中的输出:

test
123
test
123
end

Thanks.谢谢。

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

This is code that should solve your issue这是应该解决您的问题的代码

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

Notice that you just want to iterate through the list items in the for loop, then add a separate write statement for the new line before the next 'test' Also it's best to just use the escape character \n for newline within the single quotes instead of attaching it with the '+' symbol.请注意,您只想遍历 for 循环中的列表项,然后在下一个“测试”之前为新行添加一个单独的写入语句 此外,最好只在单引号内使用转义字符 \n 作为换行符用'+'符号附加它。

if you want the list to become a string follow this template如果您希望列表成为字符串,请遵循此模板

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

for i in num: str1 += i for i in num: str1 += i

print(str1)打印(str1)

output: 123输出:123

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

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