0

我知道您可以在 Python GUI 中打开文件、浏览器和 URL。但是,我不知道如何将其应用于程序。例如,以下都不起作用。(以下是我不断增长的聊天机器人程序的片段):

def browser():
    print('OPENING FIREFOX...')
    handle = webbroswer.get() # webbrowser is imported at the top of the file
    handle.open('http://youtube.com')
    handle.open_new_tab('http://google.com') 

def file():
    file = str(input('ENTER THE FILE\'S NAME AND EXTENSION:'))
    action = open(file, 'r')
    actionTwo = action.read()
    print (actionTwo)

就上述顺序而言,这些错误发生在单独的运行中:

OPENING FIREFOX...
Traceback (most recent call last):
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
    askForQuestions()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 64, in askForQuestions
    browser()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 38, in browser
    handle = webbroswer.get()
NameError: global name 'webbroswer' is not defined
>>> 

ENTER THE FILE'S NAME AND EXTENSION:file.txt
Traceback (most recent call last):
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
    askForQuestions()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 66, in askForQuestions
    file()
  File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 51, in file
    action = open(file, 'r')
IOError: [Errno 2] No such file or directory: 'file.txt'
>>> 

我是在处理这个错误,还是我不能在程序中使用 open() 和 webbrowser?

4

1 回答 1

6

您应该阅读错误并尝试理解它们 - 它们在这种情况下非常有帮助 - 因为它们通常是:

第一个说NameError: global name 'webbroswer' is not defined。您可以在此处看到webbrowser代码中的拼写错误。它还告诉您它发现错误的行(第 38 行)

第二个IOError: [Errno 2] No such file or directory: 'file.txt'告诉您您正在尝试打开一个不存在的文件。这不起作用,因为您指定了

    action = open(file, 'r')

这意味着您正在尝试读取文件。Python 不允许读取不存在的文件。

于 2012-08-21T00:13:23.997 回答