【问题标题】:Write a multi line string to a text file using Python使用 Python 将多行字符串写入文本文件
【发布时间】:2020-01-22 04:53:20
【问题描述】:

我正在尝试将多行字符串写入 Python3 中的文本文件,但它只写入单行。

例如

假设打印我的字符串会在控制台中返回这个;

>> print(mylongstring)
https://www.link1.com
https://www.link2.com
https://www.link3.com
https://www.link4.com
https://www.link5.com
https://www.link6.com

然后我将其写入文本文件

f = open("temporary.txt","w+")
f.write(mylongstring)

在我的文本文件中读取的所有内容都是第一个链接 (link1.com)

有什么帮助吗?如果您愿意,我可以详细说明,毕竟这是我在这里的第一篇文章。

【问题讨论】:

  • 这能回答你的问题吗? write multiple lines in a file in python
  • print(type(mylongstring)) 的结果是什么?
  • 请分享您的长字符串变量的外观。
  • 请分享print(repr(mylongstring))
  • 所以它是一个字符串列表,而不是“多行字符串”。这两件事完全不同。请确保您的问题是正确的。

标签: python python-3.x


【解决方案1】:

永远不要打开文件而不在最后再次关闭它。 如果您不希望打开和关闭喧嚣使用上下文管理器,它将处理文件的打开和关闭。

    x = """https://www.link1.com
            https://www.link2.com
            https://www.link3.com
            https://www.link4.com
            https://www.link5.com
            https://www.link6.com"""

    with open("text.txt","w+") as f:
        f.writelines(x)

【讨论】:

    【解决方案2】:

    尝试关闭文件:

    f = open("temporary.txt","w+")
    f.write(mylongstring)
    f.close()
    

    如果这不起作用,请尝试使用:

    f = open("temporary.txt","w+")
    f.writelines(mylongstring)
    f.close()
    

    如果仍然不起作用,请使用:

    f = open("temporary.txt","w+")
    f.writelines([i + '\n' for i in mylongstring])
    f.close()
    

    【讨论】:

    • 逐个字母打印出第一个字符串
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多