我仅尝试在此文件中的某些部分之后追加,我希望能够通过字符串值找到特定部分然后添加到其中。
\\ desk
\\ phone
\\ chairs
\\tv
看起来像这样
\\desk # CODE finds '\\desk' then appends below it or above
wood
metal
etc
\\phone # CODE finds '\\phone' then appends below it or above
cell
landline
etc
\\chairs
\\tv
我知道解决方案可能非常简单,我发誓我以前做过,但是显然我一直在向google /互联网的其余部分询问错误的问题。
如果基本上需要更多说明,我有一个函数可以接收args,该函数将根据所选内容追加某些节,并且必须运行多次,因此我相信追加是必须的方法。
尝试一下:
def append(filename, **args):
with open(filename) as f:
text = [x for x in f.read().splitlines() if x]
for k, v in args.items():
k = r"\\ "+k
if k not in text:
continue
i = text.index(k)
for n in reversed(v):
text.insert(i+1, n)
return "\n".join(text)
print(append(
"file.txt",
desk=["wood", "metal", "etc"],
phone=["cell", "landline", "etc"]
))
输出:
\\ desk
wood
metal
etc
\\ phone
cell
landline
etc
\\ chairs
\\tv
希望这会有所帮助:)