我有一个Discord机器人,可以读写文本文件。我输入:
+add <url>
,它将在文本文件的新行中添加一个URL。
我需要+remove <url>
才能删除在同一文本文件中与之匹配的URL。
@bot.command()
async def add(ctx, args):
url = args.lower() + '\n'
with open('text.txt', 'a') as url_file:
url_file.write(url)
@bot.command()
async def remove(ctx, args):
url = args.lower() + '\n'
with open("text.txt", 'r') as url_file:
urls = url_file.readlines()
replacement_urls = [url for url in urls if url != x]
with open('text.txt', 'w') as url_file:
url_file.truncate()
url_file.write(''.join(replacement_urls))
+ add可以正常工作,但是当我运行remove命令时,我得到了错误
replacement_urls = [url for url in urls if url != x] NameError: name 'x' is not defined
有什么建议吗?
答案 0 :(得分:0)
您将输入网址命名为url
,但是在列表理解中,您将url
重新分配给urls
的每个元素。
replacement_urls = [x for x in urls if x != url]