如何更新文本文件中的变量

时间:2013-08-04 07:11:03

标签: python file variables python-3.x

我有一个程序可以打开一个帐户并且有几行,但是我希望它更新这一行credits = 0每当购买时,我希望它再添加一个金额,这就是文件的内容看起来像

['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']

credits = 0

这些信息保存在文本文件中我不在乎你是否更换它(只要它还有1个)或者你是否只是更新它。请帮帮我:)抱歉,如果这个问题很简单

2 个答案:

答案 0 :(得分:3)

下面的代码段应该可以让您了解如何进行操作。此代码更新,文件中存在的计数器变量的值 counter_file.txt

import os

counter_file = open(r'./counter_file.txt', 'r+')
content_lines = []

for line in counter_file:
        if 'counter=' in line:
                line_components = line.split('=')
                int_value = int(line_components[1]) + 1
                line_components[1] = str(int_value)
                updated_line= "=".join(line_components)
                content_lines.append(updated_line)
        else:
                content_lines.append(line)

counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()

希望这可以解释如何解决问题

答案 1 :(得分:1)

您可以根据字典创建一般文本文件替换器,该字典包含要作为键查找的内容以及要替换的对应值:

在模板文本文件中放置一些你想要变量的标志:

['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']

credits = <credit_var>

然后创建一个映射字典:

map_dict = {'<namef>':'New name', '<credit_var>':1}

然后重写执行替换的文本文件:

newfile = open('new_file.txt', 'w')
for l in open('template.txt'):
    for k,v in map_dict.iteritems():
        l = l.replace(k,str(v))
    newfile.write(l)
newfile.close()