【问题标题】:Retrieving information from text file从文本文件中检索信息
【发布时间】:2021-02-09 00:50:57
【问题描述】:

我想接受用户输入的变量“name”,然后我想将account.zk(这是一个普通的文本文件)加载到一个列表中,然后我想检查是否输入已在此列表中。如果不是,我想添加它,相反,我想跳过并继续。

我自己编写了这个函数,但我没有成功!有人能理解为什么吗?

# Start Downloading System
name = input(Fore.WHITE+"Enter Profile Name To Download: ")

# Save Account (used for check the updates!)
file_object = open("account.zk", "r")

for line in file_object:
  stripped_line = line.strip()
  line_list = stripped_line.split()
  list_of_lists.append(line_list)


if (len(list_of_lists) != len(set(name))):
    print("\n\nAlready in List!\n\n")
    file_object.close
    time.sleep(5)
else:
    file_object.close
    file_object = open("account.zk", "w")
    file_object.write(name + "\n")
    file_object.close

【问题讨论】:

  • 'list_of_list' 显然已经声明了!
  • 您可能想访问this link 以比较文件打开模式 - 当您第二次以“w”模式打开它时,它会被您所在的单行覆盖写给它。使用“a”附加。除此之外,您对.close() 的调用缺少括号。然后,检查它是否“已经在列表中!”的逻辑似乎完全格格不入。也许你应该把list_of_lists变成一个元组列表,然后if tuple(name) in list_of_tuples: ...
  • 如果您正在使用 IDE现在是学习其调试功能的好时机 - 例如设置断点和检查值。或者你可以花点时间熟悉一下内置的Python debugger。此外,在程序的关键点打印 stuff 可以帮助您跟踪正在发生或未发生的事情。

标签: python list filter fopen txt


【解决方案1】:

我认为你想要做的是:

# Start Downloading System
name = input(Fore.WHITE + "Enter Profile Name To Download: ")

# Save Account (used for check the updates!)
file_object = open("account.zk", "r")

list_of_lists = []
for line in file_object:
  stripped_line = line.strip()
  line_list = stripped_line.split()
  list_of_lists.extend(line_list)  # add the elements of the line to the list

if name in list_of_lists:  # check if the name is already in the file
    print("\n\nAlready in List!\n\n")
    file_object.close()
    time.sleep(5)
else:  # if not, add it
    file_object.close()
    file_object = open("account.zk", "w")
    file_object.write(name + "\n")
    file_object.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2019-10-10
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多