0

这是我的代码:

print "Note: Your file is available now."
viewYourFile = raw_input("\nDo you wish to view this file now? ")

if viewYourFile == 'Y' or 'y':
    fo = open('messages.txt', 'r+')
    #Read whole file into data
    data = fo.read()
    print data
    # Close the file
    fo.close()
elif viewYourFile == 'N' or 'n': 
    print "Thank you!"
else:
    print "Didn't recognize user input"

当我输入“n”时,文本文件仍然打开。如果用户输入“N”或“n”,我希望脚本继续运行而不将文本打印到终端中。

我看不出我做错了什么明显的事情。有人可以再看看我吗?非常感谢。

4

3 回答 3

3

if viewYourFile == 'Y' or 'y':True由于第二个条件'y'是 always ,因此总是计算为True

>>> bool('y')
True
>>> bool(False or 'y')
True

改为使用if viewYourFile in ('Y', 'y'):

此外,不要手动关闭文件,而是使用with上下文管理器。这是生成的代码:

print "Note: Your file is available now."
viewYourFile = raw_input("\nDo you wish to view this file now? ")

if viewYourFile in ('Y', 'y'):
    with open('messages.txt', 'r+') as fo:
        data = fo.read()
elif viewYourFile in ('N', 'n'): 
    print "Thank you!"
else:
    print "Didn't recognize user input"

另见:

于 2013-09-05T11:49:20.780 回答
2

你应该做:

if viewYourFile == 'Y' or viewYourFile == 'y':

或像@alecxe建议的那样,即:

if viewYourFile in ('Y', 'y'):

另一个减少打字的好方法是:

if viewYourFile.lower() == 'y':
于 2013-09-05T11:52:35.120 回答
1

我认为更聪明的是导致一个寄存器:

if viewYourFile.lower() == 'y':
于 2013-09-05T11:51:54.433 回答