【问题标题】:Why doesn't the file open? (Python)为什么文件打不开? (Python)
【发布时间】:2018-02-25 01:18:17
【问题描述】:

每当我尝试输入“C.elegans_small.gff”时,程序都会给出“无法打开”的打印语句。但是,我希望它打开。为什么会这样?

print("Gene length computation for C. elegans.")
print()
file1 = "C.elegans_small.gff"
file2 = "C.elegans.gff"
user_input = input("Input a file name: ")
while user_input != file1 or user_input != file2:
    print("Unable to open file.") 
    user_input = input("Input a file name: ")
    if user_input == file1 or user_input == file2:
        break

【问题讨论】:

  • 总是不是一个或另一个。将测试反转为and
  • not file1 or not file 2 <=> not (file1 and file2) 这总是正确的......你的意思是not file1 and not file2 <=> not(file1 or file2)

标签: python openfiledialog


【解决方案1】:

您的代码不正确,因为您使用的是or 而不是and

假设用户输入 file1,那么 if 语句是 False or True

因为它是or 而不是and,如果其中一个语句是true,它仍然会在while 循环中。打破 while 循环的唯一方法是输入同时等于 file1 和 file2。

这是使用 and 时代码的固定版本。

print("Gene length computation for C. elegans.")
print()
file1 = "C.elegans_small.gff"
file2 = "C.elegans.gff"
user_input = input("Input a file name: ")
while user_input != file1 and user_input != file2:
    #now if one is true it exits
    print("Unable to open file.") 
    user_input = input("Input a file name: ")

另外,这部分没用。这是因为 while 循环会检查它并自行中断,因此您不需要 if 语句来中断它。

if user_input == file1 or user_input == file2:
        # This stays as or because if one is true you want it to pass
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2021-09-04
    • 2021-09-01
    • 2015-07-06
    • 2021-06-16
    相关资源
    最近更新 更多