正在尝试做一个测试!=选择但失败

2024-04-26 04:49:23 发布

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

我想做一个选项,打开一个文本文件,输入可以是一个.txt和结束,没有。到目前为止,对于我提供的代码,当我不包含“.txt”时,它可以工作,但当我包含“.txt”时,它会添加一个“.txt”,从而导致错误

if choice == 'r':
           fileName = input("Enter the file name: ")
           if fileName!= fileName.endswith('.txt'):
               fileName= fileName + '.txt'
               readEmployees(fileName)

readEmployees稍后用于读取文件和显示名称


3条回答

endswith()方法返回true或false。因此,if语句应该只包含endswith()方法,而不是将其与文件名进行比较。另外,我猜您想调用readEmployees(filename),不管它是否以.txt结尾。因此,您应该将其放在if语句之外,因为当前代码仅在文件不以.txt结尾时调用它

if choice == 'r':
    fileName = input("Enter the file name: ")
    if not fileName.endswith('.txt'):
       fileName = fileName + '.txt'
    readEmployees(fileName)

正如其他答案所指出的,问题在于将字符串与布尔值进行比较:

>>> fileName = "file.txt"
>>> fileName
'file.txt'
>>> fileName.endswith(".txt")
True

只是一个旁注:这里有一个更简洁的方法,虽然用三元运算符编写代码可能不太容易:

if choice == "r":
    fileName = input("Enter the file name: ")
    fileName += ".txt" if not fileName.endswith(".txt") else ""
    readEmployees(fileName)

阅读关于ternary operators here

如果没有所需的输出,我无法确定,但你是想写

if choice == 'r':
           fileName = input("Enter the file name: ")
           if not fileName.endswith('.txt'):
               fileName= fileName + '.txt'
               readEmployees(fileName)

基本上,.endswith()返回一个布尔值,因此您将filename与布尔值进行比较

相关问题 更多 >

    热门问题