我正在编写一个程序,该程序将从模板中提取变量并有效地将“查找/替换”到模板中。
示例模板:
VARIABLES
@username
@password
@secret
###########################################################
My username is @username
Password is @password
Secret is @secret
该程序将找到每个变量,并逐个询问用户输入,打开文件,保存内容,然后关闭文件以准备下一个变量。
除了一个奇怪的以外,其他一切都运转良好。运行代码后,文本文件的末尾似乎有点疯狂。参见下面的输出。如您所见,它成功地获取了变量并将其放置,但是它在末尾添加了“ TESTis TESTetis @secret”吗?
VARIABLES
User
Pass
TEST
###########################################################
My username is User
Password is Pass
Secret is TESTis TESTis TESTetis @secret
我是Python的新手(本周),请谅解下面的代码。我以自己的特殊方式使它起作用!它可能不是最有效的。只是努力查看在哪里添加了额外的内容。
代码:
##COPY CONTENTS FROM READ ONLY TO NEW FILE
with open("TestTemplate.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line)
fin.seek(0)
fout.seek(0)
fin.close()
fout.close()
##PULL VARIABLES AND FIND/REPLACE CONTENTS
with open("out.txt", "rt") as fin:
with open("out.txt", "rt") as searchf:
with open("out.txt", "r+") as fout:
for line in fin:
if line.startswith("@"):
trimmedLine = line.rstrip()
## USER ENTRY
entry = input("Please Enter " + trimmedLine + ": ")
for line in searchf:
## ENSURE ONLY VARIABLES AFTER '#' ARE EDITED. KEEPS IT NEAT
if trimmedLine in line:
fout.write(line.replace(trimmedLine,entry))
else:
fout.write(line)
##RESET FOCUS TO THE TOP OF THE FILE READY FOR NEXT ITERATION
searchf.seek(0)
fout.seek(0)
提前致谢
相关分类