为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Python 将多行字符串写入文本文件

使用 Python 将多行字符串写入文本文件

慕斯王 2022-07-05 15:47:23
我正在尝试将多行字符串写入 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)


查看完整回答
反对 回复 2022-07-05
?
叮当猫咪

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


查看完整回答
反对 回复 2022-07-05
  • 2 回答
  • 0 关注
  • 500 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号