如何在python中将字符串保存为字符串?

问题描述 投票:0回答:1

我有一个文件file.md,我想读取并将其作为字符串获取。然后,我想使用该字符串并将其保存在另一个文件中,但是作为带引号的字符串(和全部)。原因是我想将markdown文件的内容传输到markdown字符串,以便可以使用javascript marked库将其包含在html中。

如何使用python脚本来做到这一点?

这是我到目前为止尝试过的?

with open('file.md', 'r') as md:
    text=""
    lines = md.readlines()
    for line in lines:
        line = "'" + line + "'" + '+'
        text = text + line
    with open('file.txt', 'w') as txt:
        txt.write(text)

输入文件.md

This is one line of markdown
This is another line of markdown

This is another one

所需输出文件.txt

"This is one line of markdown" +
"This is another line of markdown" +
(what should come here by the way to encode an empty line?)
"This is another one"
python string file save read-write
1个回答
0
投票

这里需要注意两件事。首先,在迭代器line通过lines运行时,请勿更改它。而是将其分配给新的字符串变量(我称其为new_line)。其次,如果在每个line的末尾添加更多字符,则它将被放置在行尾字符之后,因此在将其写入新文件时将其移至下一行。而是跳过每行的最后一个字符并手动添加换行符。

如果我理解的正确,这应该给您想要的输出:

with open('file.md', 'r') as md:
    text = ""
    lines = md.readlines()

for line in lines:
    if line[-1] == "\n":
        text += "'" + line[:-1] + "'+\n"
    else:
        text += "'" + line + "'+"

with open('file.txt', 'w') as txt:
    txt.write(text)

注意最后一行与其他行之间的区别(没有eol-char,没有+号)。text += ...将更多字符添加到现有字符串。

这也可以,并且可能会更好一些,因为它避免了if语句。您可以在从file.md读取内容时删除换行符。最后,您跳过内容的最后两个字符,即+\n

with open('file.md', 'r') as md:
    text = ""
    lines = [line.rstrip('\n') for line in md]

for line in lines:
    text += "'" + line + "' +\n"

with open('file.txt', 'w') as txt:
    txt.write(text[:-2])

...并使用格式化程序:

text += "'{}' +\n".format(line)
© www.soinside.com 2019 - 2024. All rights reserved.