导入webbrowser后Python写入config.ini报错:bool对象不支持上下文管理器
问题排查:导入webbrowser模块后config.ini写入失败
原本用于写入config.ini的代码可正常运行,但添加from webbrowser import *导入语句后,写入操作抛出类型错误。
可正常运行的代码
import configparser config = configparser.ConfigParser() # Add the structure to the file we will create config.add_section('pos') config.set('pos', 'x', '0') config.set('pos', 'y', '0') # Write the new structure to the new file with open(r"C:/Users/gberg/Desktop/main/coding/config.ini", 'w') as configfile: config.write(configfile)
无法运行的代码
from webbrowser import * import configparser config = configparser.ConfigParser() # Add the structure to the file we will create config.add_section('pos') config.set('pos', 'x', '0') config.set('pos', 'y', '0') # Write the new structure to the new file with open(r"C:/Users/gberg/Desktop/main/coding/config.ini", 'w') as configfile: config.write(configfile)
报错信息
Traceback (most recent call last): File "c:\Users\gberg\Desktop\main\coding\frog_prova.py", line 19, in <module> with open(r"C:/Users/gberg/Desktop/main/coding/config.ini", 'w') as configfile: TypeError: 'bool' object does not support the context manager protocol
问题原因
from webbrowser import *会导入该模块下的所有名称,其中包括一个名为open的函数——这个函数用于打开网页,返回值是布尔类型(表示是否成功打开浏览器)。它覆盖了Python内置的open()函数,导致后续调用open()时,实际执行的是webbrowser.open(),返回的是布尔值而非文件对象。布尔值无法作为上下文管理器使用,因此触发报错;即使不用with语句,直接传递open()的返回值给config.write(),也会因为传入的是bool而非文件对象而失败。
解决方法
有两种可行的修复方式:
- 避免星号导入:改用
import webbrowser,调用网页打开功能时使用webbrowser.open(),这样不会覆盖内置的open()函数。 - 显式保留内置open:如果必须使用
from webbrowser import *,可以在导入后显式导入内置的open:
或者在调用文件打开时直接指定内置函数:from webbrowser import * from builtins import open # 导入内置open,覆盖webbrowser的open import configparser # 后续代码不变with __builtins__.open(r"C:/Users/gberg/Desktop/main/coding/config.ini", 'w') as configfile: config.write(configfile)
内容的提问来源于stack exchange,提问作者Giacomo
相关产品推荐
相关产品推荐

