【问题标题】:change .txt files with certain conditions在特定条件下更改 .txt 文件
【发布时间】:2020-11-25 02:31:27
【问题描述】:

我有带有 id 不和谐服务器编号的 txt 文件(例如:38748194014..) 该文件应如下所示:

213123123123
312312342423
64574476747457
52534653463636

所以我需要用这个文件做什么:

  1. 当一个人写一个命令时,我的机器人必须记录服务器的 id 不和谐,如果它已经存在,则显示一条消息它存在(将服务器 id 添加到 txt 文件)
  2. 当一个人写一个命令时,我的机器人应该在这个列表中找到这个服务器的 ID 并从那里删除它,如果它不在那里,显示一个错误消息(从 txt 文件中删除服务器 ID) I know how to get discord server id i need only how to add server id to txt file and delete from txt file 完整解释: 1.
 if my_server_id not found in servers_id_list:
  add my_server_id to new stroke in txt file
 else:
  print('File contain my_server_id')
 if my_server_id found in servers_id_list:
  delete my_server_id from server_id_list
 else:
  print('File not contain my_server_id')

试图尽可能清楚地解释,帮助... hee cough.. 帮助我。

【问题讨论】:

  • 不幸的是,像这样的问题通常无法在 StackOverflow 上回答,因为看起来您实际上并没有尝试编写代码来做您想做的事情。 (您编写的内容看起来像伪代码。)有关更多信息,请参阅this

标签: python python-3.x discord discord.py


【解决方案1】:

似乎文本文件对此并不理想(我会使用数据库),但要在末尾添加一些内容:

with open(file, 'a') as f:
    f.write(id)

对于删除,您可能必须将整个文件读入一个数组,然后对其进行修改并重新写回。

https://docs.python.org/3/tutorial/inputoutput.html

【讨论】:

    【解决方案2】:

    这是工作代码:

    f=open("data.txt","r") #use any file name you want
    lines=[]
    for line in f:
        lines.append(line.strip())
    f.close()
    def check_add(sid):
        if str(sid) in lines:
            print('File contain my_server_id')
        else:
            lines.append(check_id)
    
    def check_delete(sid):
        if str(sid) in lines:
            lines.remove(check_id)
        else:
            print('File not contain my_server_id')
        
    check_id=input() #server id
    check_add(check_id) # or check_delete(check_id), depends which function you need
    
    
    f_app=open("data.txt","w") #use any file name you want, this is for writing result to file after changes
    for l in lines:
        f_app.write(l+"\n")
    f_app.close()
    

    如您所述,您有 2 个功能。第一个检查,如果没有 id 它添加它。第二个检查 id 是否存在,如果存在则将其删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多