【发布时间】:2018-05-25 14:10:47
【问题描述】:
我正在编写一个寻找一些东西的不和谐机器人:
1) 它检查发送命令的用户名是否已经在文件中,发送消息的用户是“成员”变量。
2) 如果用户不在文件中,则应将其姓名添加到文件中。
3) 如果用户在文件中,它会向他们发送一条消息,说他们不能添加他们的名字两次。
下面的代码我尝试了不同的变体,但仍然无法完全理解。 Print (current_name) 在那里,所以我可以查看代码是否循环遍历文本文件的所有行,并且只有当我尝试读取文件的行并查看成员是否不在其中时,它才会打印所有要安慰的名字。如果您需要更多代码,请 lmk。
source_file_name = 'tracker.txt'
temporary_file_name = 'tracker_temp.txt'
with open(source_file_name, mode='r') as source_file:
with open(temporary_file_name, mode='w') as temporary_file:
for current_line in source_file:
line_splitted = current_line.split()
current_name = line_splitted[0]
print(current_name)
if str(member) not in source_file.readlines():
output_line = str(member) + "\n"
temporary_file.write(output_line)
elif current_name == str(member):
output_line = str(member) + "\n"
mporary_file.write(output_line)
await client.send_message(message.channel, "You cannot redeem another role while your other role is still active!")
else:
output_line = current_name + "\n"
temporary_file.write(output_line)
os.replace(temporary_file_name, source_file_name)
【问题讨论】:
-
问题是什么?
-
建议而不是解决方案:使用字典、列表或您喜欢的其他对象来存储有关用户的信息,并且仅定期将数据转储到文件中。让您的程序不断解析文件听起来并不理想。
-
将工作流程分解为是否准确:1) 获取文件中的名称 2) 确定“成员”是否是步骤 1 中的名称之一 3) 将成员添加到如果第 2 步为假,则归档 4) 如果第 2 步为真,则回复用户?
-
你能提供一个示例输入文件吗?