3

我有一个打开帐户的程序,有几行,但我希望它更新这一行credits = 0每当购买时,我希望它再增加一个金额,这就是文件的样子

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

credits = 0

这段信息保存在一个文本文件中 请帮帮我:)对不起,如果这个问题很琐碎

4

2 回答 2

4

下面的代码片段应该让您了解如何进行。此代码更新文件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()

希望这对如何解决您的问题有所帮助

于 2013-08-04T08:02:51.937 回答
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()
于 2013-08-04T07:21:10.057 回答