在python中替换输出文件中的路径名

2024-03-29 00:07:58 发布

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

我需要一个Python代码来替换通过导入的文本模板中的占位符(“%p%”)

text_in = open(self.filename1, 'r') 

通过tkinter写入来自输入的路径名 tkFileDialog.askopenfilename文件名. 模板完全读入。通过编写文本文件,占位符应替换为保存在变量中的路径名

self.filename = tkFileDialog.askopenfilename

我用get()方法尝试过,比如

replacements = {'%p%':self.filelocation.get(),'%r%':self.filelocation1.get()}
for line in text_in:
 for src, target in replacements.iteritems():
   line = line.replace(src, target)
 text_out.write(line)
text_in.close()

但它并不像预期的那样工作。我的问题是,当文本文件被临时读取并写入文本文件时,是否可以使用get()方法对内容进行操作,或者是否需要替换已硬编码的文件名?我希望有人有什么想法。你知道吗


Tags: 方法textinselfsrc模板forget