Python 向txt文件添加新值
当用户启动我的机器人时,它会获取其用户id并将其存储在.txt文件中Python 向txt文件添加新值,python,python-3.x,file,bots,fwrite,Python,Python 3.x,File,Bots,Fwrite,当用户启动我的机器人时,它会获取其用户id并将其存储在.txt文件中 def verify_id(update, context): __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) f = open(os.path.join(__location__, 'users_list_file.txt'), 'w+') f_content = f.read(
def verify_id(update, context):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
f = open(os.path.join(__location__, 'users_list_file.txt'), 'w+')
f_content = f.read().strip().split()
registered = False
user_id = str(update.message.from_user.id)
if user_id in f.read():
message_ok = "User already existing in DB"
update.message.reply_text(message_ok)
registered = True
else:
f.write(user_id)
message_added = "You have been added to my list :)"
update.message.reply_text(message_added)
f.close()
目标:
,打开('file_name.txt','a+')作为文件:
文件写入(数据)
“a”标志用于附加。”w'将写入文件,但将覆盖其内容。
打开文件时,请注意将与
一起使用。这样,您就不必担心在完成后关闭文件。注意在每个write语句中添加换行符
file.write('\n'+id)
问题中提供的代码每次
('w+')
写入数据并替换旧值。我建议您维护一个包含用户ID列表的字典,并在列表发生变化时进行更新,然后写入,否则只发送一条消息,而不是维护一行一行的简单书写(如果您必须检查以后的用户,这将始终是个问题)
下面是一个类似的简单示例:
import os
import json
def verify_id(user_id):
if not os.path.exists("example_users.json"):
users = {}
users_list = []
else:
f = open("example_users.json")
users = json.load(f)
users_list = users["users"]
if user_id not in users_list:
users_list.append(user_id)
users["users"] = users_list
# Rewrite
with open("example_users.json", 'w') as f:
json.dump(users, f)
else:
#Some message
print("Already present")
以下是json在某些用户中的外观:
{"users": [1, 132]}
让我们添加相同的用户:
verify_id(1)
Already present
新用户:
verify_id(123)
json updated: {"users": [1, 132, 123]}
使用json的好主意。谢谢有趣。我不知道这会是一次不同的手术。我将尝试两种解决方案,因为它们都非常好。