如何在Python中打开文件,Web浏览器和URL,而不是在IDLE中。

时间:2012-08-21 00:05:50

标签: python file browser

我知道您可以在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?

1 个答案:

答案 0 :(得分: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不允许从不存在的文件中读取。