我想做的是将值写入文件的特定部分。这个部分可以在文件中的任何地方,但只会出现一次,因此我不相信添加一行就能解决它。在
我所拥有的基本上是一个文本文件:
TitleThing (
Some info = 22
(More info = 22.2)
Tags = []
)
我想做的是在Tags=后面的[]中的文件中添加一个字符串。在
看起来像:
^{pr2}$另一个问题是可能存在现有标记:
TitleThing (
Some info = 22
(More info = 22.2)
Tags = ["oldtag, othertag"]
)
在这种情况下,我想把我的“newtag”添加到退出列表中,以便它首先出现。在
我从以下几点开始:
tagRegex = re.compile(r'Tags = [(.*)]')
但我不知道该怎么办。在
希望能帮忙!在
谢谢。在
您需要写入临时文件,然后覆盖原始文件。在
然后传入新值:
^{pr2}$如果您希望在开始时使用新值,只需稍微改变一下逻辑即可:
根据您的评论,将if更改为:
一个肮脏的想法:你可以用
Tags = ...
来读一行,计算它,编辑列表,然后重写它:其中
f
是一个新文件,您可以在其中编写编辑过的版本(或在另一个答案中使用临时文件)。在(当然,执行任意字符串总是很危险的,但如果它是一次性脚本,则可以这样做。)
相关问题 更多 >
编程相关推荐