简体   繁体   English

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

[英]Write a multi line string to a text file using Python

I'm trying to write multiple lines of a string to a text file in Python3, but it only writes the single line.我正在尝试将多行字符串写入 Python3 中的文本文件,但它只写入单行。

eg例如

Let's say printing my string returns this in the console;假设打印我的字符串在控制台中返回它;

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

And i go to write that into a text file我去把它写成一个文本文件

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

All that reads in my text file is the first link (link1.com)我的文本文件中读取的所有内容都是第一个链接(link1.com)

Any help?有什么帮助吗? I can elaborate more if you want, it's my first post here after all.如果你愿意,我可以详细说明,毕竟这是我在这里的第一篇文章。

Try closing the file:尝试关闭文件:

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

If that doesn't work try using:如果这不起作用,请尝试使用:

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

If that still doesn't work use:如果这仍然不起作用,请使用:

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

never open a file without closing it again at the end.永远不要打开文件而不在最后再次关闭它。 if you don't want that opening and closing hustle use context manager with this will handle the opening and closing of the file.如果您不想打开和关闭喧嚣,请使用上下文管理器,这将处理文件的打开和关闭。

    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM