我正在尝试将多行字符串写入 Python3 中的文本文件,但它只写入单行。例如假设打印我的字符串在控制台中返回它;>> print(mylongstring)https://www.link1.comhttps://www.link2.comhttps://www.link3.comhttps://www.link4.comhttps://www.link5.comhttps://www.link6.com我去把它写到一个文本文件中f = open("temporary.txt","w+")f.write(mylongstring)在我的文本文件中读取的所有内容都是第一个链接 (link1.com)有什么帮助吗?如果您愿意,我可以详细说明,毕竟这是我在这里的第一篇文章。
2 回答

拉丁的传说
TA贡献1789条经验 获得超8个赞
永远不要在最后关闭文件的情况下打开文件。如果您不希望打开和关闭喧嚣使用上下文管理器,它将处理文件的打开和关闭。
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)

叮当猫咪
TA贡献1776条经验 获得超12个赞
尝试关闭文件:
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()
添加回答
举报
0/150
提交
取消