我正在尝试将字符串的多行写入 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
Run Code Online (Sandbox Code Playgroud)
我将其写入文本文件
f = open("temporary.txt","w+")
f.write(mylongstring)
Run Code Online (Sandbox Code Playgroud)
我的文本文件中读取的所有内容都是第一个链接(link1.com)
有什么帮助吗?如果您愿意,我可以详细说明,毕竟这是我的第一篇文章。
i_a*_*esh 10
切勿在最后未再次关闭文件的情况下打开文件。如果您不希望打开和关闭喧嚣,请使用上下文管理器,这将处理文件的打开和关闭。
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)
Run Code Online (Sandbox Code Playgroud)
尝试关闭文件:
f = open("temporary.txt","w+")
f.write(mylongstring)
f.close()
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,请尝试使用:
f = open("temporary.txt","w+")
f.writelines(mylongstring)
f.close()
Run Code Online (Sandbox Code Playgroud)
如果仍然不起作用,请使用:
f = open("temporary.txt","w+")
f.writelines([i + '\n' for i in mylongstring])
f.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20338 次 |
| 最近记录: |