python尝试/除了raw_input不忽略异常

时间:2015-01-06 15:44:56

标签: python

我不明白为什么我的try / except不起作用,当我运行它时,它会打印else语句,但无论如何都会引发异常。

try:
    inventory_fname = raw_input('\n\n\tWhat would you like to name your Inventory spreadsheet?\n\n\t:')
except WindowsError:
    pass
    print "Sorry, that is an invalid filename."
else:
    print "\n\n\tSorry, that is an invalid filename."

例外......

        What would you like to name your Inventory spreadsheet?

        :idiot proof?


        Sorry, that is an invalid filename.
Traceback (most recent call last):
  File ".\show_file_inventory_creation.py", line 193, in <module>
    main()
  File ".\show_file_inventory_creation.py", line 188, in main
    os.rename(inventory_dir + 'INVENTORY.xls', inventory_dir + xl_inventory_fname)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

编辑:

我已经移动了try语句,它有效,谢谢你!

inventory_fname = raw_input('\n\n\tWhat would you like to name your Inventory spreadsheet?\n\n\t:')
    xl_inventory_fname = inventory_fname + '.xls'
    #rename temporary .xls file to user's desired name
    try:
        os.rename(inventory_dir + 'INVENTORY.xls', inventory_dir + xl_inventory_fname)
    except WindowsError:
        pass
        print "\n\n\tSorry, that is an invalid filename."

0 个答案:

没有答案