为什么我的代码在文件中找不到输入编号,即使输入编号在文件中清晰可见?

2024-06-07 08:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是搜索文件中特定条目的代码:

num2find = str(input("Enter a number to find: "))

test_file = open("testfile.txt", "r")

num = "0"
flag = False
while (num != ""):
  num = test_file.readline()
  if (num == num2find):
    print("Number found.")
    flag = True
    break

if not flag:
  print("\nNumber not found.")

测试文件为:

1
2
3
4
5

如果我输入2,代码仍然输出“找不到编号”


Tags: 文件代码test目的inputifnotnum
3条回答

测试文件中的每一行都包含两个字符,即数字和换行符。由于"2"不等于"2\n",因此找不到您的号码。要解决此问题,请使用int函数分析行,因为它忽略空格(如\n)字符:

num2find = int(input("Enter a number to find: "))

flag = False
with open("testfile.txt", "r") as test_file:
    for line in test_file:
        num = int(line)
        if num == num2find:
            print("Number found.")
            flag = True
            break

if not flag:
  print("\nNumber not found.")

每次从文本文件中读取一行时,都会在字符串行的末尾得到"\n",因此您面临的问题是,您正在将"2""2\n"进行比较,这两个值是不同的

你可以利用with来写你的文件。这样,您就不必担心在完成文件后关闭它。另外,您不需要传递"r"参数,因为它是open的默认模式

您应该使用for循环,而不是不必要的while循环。读取文件中的所有行后,for循环将自动终止

您可以做的另一个改进是将标志flag重命名为found,并在处理完文件后打印结果

num2find = int(input("Enter a number to find: "))

found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
    for line in test_file: # use a for loop to iterate over each line in the file
        num = int(line)
        if num == num2find:
            found = True
            break

if found: # print results at the end once file was processed
    print("Number found.")
else:
    print("Number not found.")

在所有反馈之后,我能想到的最简单、最合理的解决方案是:

num2find = int(input("Enter a number to find: "))

file_data = open("testfile.txt", "r")

found = False
for data in file_data:
  if int(data) == num2find:
    found = True

if found:
  print("\nNumber found.")
else:
  print("\nNumber not found.")

file_data.close()

相关问题 更多 >

    热门问题