【问题标题】:How to see if a string is in a text file (kinda) ? python如何查看字符串是否在文本文件中(有点)? Python
【发布时间】: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 步为真,则回复用户?
  • 你能提供一个示例输入文件吗?

标签: python discord


【解决方案1】:

我能够理解您在最后一段中提出的问题。 你需要改变的是:

with open(source_file_name, mode='r') as source_file:
    with open(temporary_file_name, mode='w') as temporary_file:
        content = source_file.readlines() # gives you a list of all the lines
        for line in content:
            current_name = line.split(' ')[0]
            print current_name

这将导致:

# result of source_file.readlines():
# content = ['Name1 asd fgh', 'Name2 qwe rty']
# Console: 
# "Name1"
# "Name2"    

请提供更多信息,以便我提供帮助。

【讨论】:

  • 为什么要读取输出文件?除非我遗漏了什么,否则根据问题中的信息,你不可能得出你所拥有的结果。
  • 代码没有遍历所有行,因此控制台不会打印所有名称。阅读他问题的最后一段。
  • 我明白了。我错过了内容是您定义为示例输入的内容。不管怎样,我评论的第一部分是,你为什么要读入输出文件?
猜你喜欢
  • 2019-08-25
  • 2022-10-13
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
相关资源
最近更新 更多