将字符串作为单行存储在文本文件中

Store a string as a single line in a text file

我有很多包含很多字符(大约 1000-1500 个字符)的大字符串,我想使用 python 将字符串写入文本文件。但是,我需要字符串在文本文件中只占一行。

例如,考虑两个字符串:

string_1 = "Mary had a little lamb
which was as white
as snow"

string_2 = "Jack and jill
went up a hill 
to fetch a pail of
water"

当我将它们写入文本文件时,我希望字符串只占一行而不是多行。

文本文件例如:

Mary had a little lamb which was as white as snow
Jack and Jill went up a hill to fetch a pail of water

如何做到这一点?

您可以使用括号将字符串拆分为多行:

s = (
    "First line "
    "second line "
    "third line"
)

您还可以使用三引号并使用 stripreplace:

删除换行符
s = """
First line
Second line
Third line
""".strip().replace("\n", " ")
In [36]: string_1 = "Mary had a little lamb which was as white as snow"
    ...:
    ...: string_2 = "Jack and jill went up a hill to fetch a pail of water"
In [37]: s = [string_1, string_2]

In [38]: with open("a.txt","w") as f:
    ...:     f.write(" ".join(s))
    ...:

从多行字符串构造单行,然后正常写入文件。你的例子真的应该使用三引号来允许多行字符串

string_1 = """Mary had a little lamb
which was as white
as snow"""

string_2 = """Jack and jill
went up a hill 
to fetch a pail of
water"""
with open("myfile.txt", "w") as f:
    f.write(" ".join(string_1.split("\n")) + "\n")
    f.write(" ".join(string_2.split("\n")) + "\n")
with open("myfile.txt") as f:
    print(f.read())

输出

Mary had a little lamb which was as white as snow
Jack and jill went up a hill  to fetch a pail of water
total_str = [string_1,string_2]  
with open(file_path+"file_name.txt","w") as fp:  
     for i in total_str:
         fp.write(i+'\n')
     fp.close()

如果您希望所有字符串都写在文件中的一行上,并且它们之间没有换行符,可以使用多种方法,如其他人所示。

有趣的问题是如何在需要时将它们重新返回到程序中,以及如何将它们返回到适当的变量中。

我喜欢使用 json(文档 here)来处理这种事情,您可以将其全部输出到一行。这个:

    import json

    string_1 = "Mary had a little lamb which was as white as snow"

    string_2 = "Jack and jill went up a hill to fetch a pail of water"

    strs_d = {"string_1": string_1, "string_2": string_2}

    with open("foo.txt","w") as fh:
        json.dump(strs_d, fh)

会将以下内容写入文件:

{"string_1": "Mary had a little lamb which was as white as snow", "string_2": "Jack and jill went up a hill to fetch a pail of water"}

这可以很容易地重新加载回字典中,并且可以拉回原始字符串。

如果您不关心原始字符串变量的名称,那么您可以使用这样的列表:

    import json

    string_1 = "Mary had a little lamb which was as white as snow"

    string_2 = "Jack and jill went up a hill to fetch a pail of water"

    strs_l = [string_1, string_2]

    with open("foo.txt","w") as fh:
        json.dump(strs_l, fh)

它输出这个:

["Mary had a little lamb which was as white as snow", "Jack and jill went up a hill to fetch a pail of water"]

从文件中重新加载时,会将所有字符串重新放入一个列表中,然后可以将其拆分为单独的字符串。

这一切都假设你想重新加载字符串(所以不要介意输出中的额外 json 信息以允许重新加载)而不是仅仅希望它们输出到文件中其他需要并且不能在输出中包含额外的 json 格式。

你的示例输出没有这个,但是你的示例输出也不止一行,问题想把它全部放在一行上,所以你的需求并不完全清楚。