我有一个文件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)
输入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"
这里需要注意两件事。首先,在迭代器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)
...按照评论中的要求检查空行:
for line in lines:
if line == '':
text += '\n'
else:
text += "'{}' +\n".format(line)
此作品:
>>> 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"
您可以自己对文件进行读写。