Python不特定于Regex的行写入

2024-09-30 14:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是将值写入文件的特定部分。这个部分可以在文件中的任何地方,但只会出现一次,因此我不相信添加一行就能解决它。在

我所拥有的基本上是一个文本文件:

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 = [(.*)]')

但我不知道该怎么办。在

希望能帮忙!在

谢谢。在


Tags: 文件字符串标记infomore地方tags情况
2条回答

您需要写入临时文件,然后覆盖原始文件。在

from tempfile import NamedTemporaryFile
from shutil import move


def add_new(new):
    with open("check.txt") as f, NamedTemporaryFile("w",delete=False) as tmp:
        for line in f:
            if line.startswith("Tags ="):
                repl = ", {}]".format(new) if "[]" not in line else "{}]".format(new)
                tmp.write(line.replace("]", repl))
                tmp.writelines(f)
                break
            tmp.write(line)
    move(tmp.name, "check.txt")

然后传入新值:

^{pr2}$

如果您希望在开始时使用新值,只需稍微改变一下逻辑即可:

   repl = "[{}, ".format(new) if "[]" not in line else "[{}".format(new)
   tmp.write(line.replace("[", repl))

根据您的评论,将if更改为:

if  '"Tags": [' in line:

一个肮脏的想法:你可以用Tags = ...来读一行,计算它,编辑列表,然后重写它:

exec('Tags = ["newtag"]')
Tags.append("othertag")
f.write('Tags = {}'.format(Tags))

其中f是一个新文件,您可以在其中编写编辑过的版本(或在另一个答案中使用临时文件)。在

(当然,执行任意字符串总是很危险的,但如果它是一次性脚本,则可以这样做。)

相关问题 更多 >