[英]How to update a variable in python 3.6 to that of a string of text in a .txt file
[英]how to update a variable in a text file
我有一个打开帐户的程序,有几行,但我希望它更新这一行credits = 0
每当购买时,我希望它在金额上再增加一个,这就是文件的样子
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
这条信息保存在一个文本文件中我不在乎你是否替换它(只要它还有 1 个)或者你是否只是更新它。 请帮帮我 :) 对不起,如果这个问题很简单
下面的代码段应为您提供有关操作方法的想法。 此代码更新文件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()
希望这可以阐明如何解决您的问题
您可以基于字典创建通用文本文件替换器,该字典包含要查找的内容作为键以及要替换的对应值:
在模板文本文件中,将一些标志放在需要变量的位置:
['<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()
您可以使用现有文件,而不是创建像 new_file.txt 或 template.txt 这样的新文件。 这里我使用client_name
和client_credit_score
作为反映用户数据的占位符:
client_name="Joseph"
client_credit_score=1
map_dict = {'<namef>':f'{client_name}', '<credit_var>':f'{client_credit_score}'}
template = """['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = <credit_var>"""
with open('existing_file.txt', 'w') as f:
for k,v in map_dict.items():
template = template.replace(k,str(v))
f.write(template)
这里的existing_file.txt
最初会有这段代码(就像你问的那样):
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
多亏了map_dict
,所有键都将更新为文件中的新值。 这是 output 的样子:
['Joseph', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 1
注意:特别感谢@Saullo 和@Tarun 的上述回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.