【问题标题】:How to write to a file in python without adding a new line except at certain place?如何在 python 中写入文件而不在特定位置添加新行?
【发布时间】: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


【解决方案1】:
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')

【讨论】:

    【解决方案2】:

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

    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 作为换行符,而不是用“+”符号附加它。

    【讨论】:

      【解决方案3】:

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

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

      对于 i in num: str1 += 我

      打印(str1)

      输出: 123

      【讨论】:

        猜你喜欢
        • 2013-04-19
        • 1970-01-01
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        • 2016-03-07
        • 2011-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多