【问题标题】:How to save a string in a file as a quoted string?如何将文件中的字符串保存为带引号的字符串?
【发布时间】:2020-05-04 20:27:29
【问题描述】:

我有一个文件file.md,我想读取它并将其作为字符串获取。 然后我想获取该字符串并将其保存在另一个文件中,但作为带有引号(和所有)的字符串。原因是我想将我的降价文件的内容传输到降价字符串,以便我可以使用 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)

输入file.md

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

This is another one

所需输出:file.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"

【问题讨论】:

  • 您的输出文件是什么样的?它与您想要的有什么不同?
  • 所以你想要的只是从文件中读取的文本前后的引号?
  • @MAK 基本上我想要一个字符串在我的文本文件中
  • @moctarjallo 您能否举一个所需输出的示例,就像它在目标文件中一样?

标签: python string file save read-write


【解决方案1】:

这里有两点需要注意。 首先是你不应该改变你的迭代器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)

...按照您在 cmets 中的要求检查空行:

for line in lines:
    if line == '':
        text += '\n'
    else:
        text += "'{}' +\n".format(line)

【讨论】:

  • 此输出与描述的内容接近,但与描述的不完全一致。
  • 我刚刚在他的问题中看到了编辑。唯一的区别是+ 之前的空白。除此之外,它只是归结为' '" ",两者都在问题中提出并且可以轻松互换。
  • 最后一行的末尾也不应该有+
  • 是的,这就是存储text[:-2] 的原因。倒数第二个字符是+,最后一个是\n
  • 很好,但这没有考虑空行。我已经编辑了问题(输入和输出文件)来解决这个问题。
【解决方案2】:

这行得通:

>>> a = '''This is one line of markdown
... This is another line of markdown
... 
... This is another one'''
>>> lines = a.split('\n')
>>> lines = [ '"' + i + '" +' if len(i) else i for i in lines]
>>> lines[-1] = lines[-1][:-2]   # drop the '+' at the end of the last line
>>> print '\n'.join( lines )
"This is one line of markdown" +
"This is another line of markdown" +

"This is another one"

您可以自己添加对文件的读/写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 2022-11-21
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多