【发布时间】:2023-02-21 06:41:52
【问题描述】:
如果您的问题作为此问题的副本而被关闭,那是因为您的代码如下:
from os import *
with open('example.txt', mode='r') as f:
print('successfully opened example.txt')
这会导致显示 TypeError: open() missing required argument 'flags' (pos 2) 的错误消息。
或者,您可能尝试将 mode 指定为位置参数而不是关键字参数,例如:
from os import *
with open('example.txt', 'r') as f:
print('successfully opened example.txt')
但这也不起作用——它给出了一个不同的错误,即TypeError: an integer is required (got type str)。
你可能已经注意到内置的open函数没有这样的关键字参数flags:
>>> help(open)
Help on built-in function open in module io:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
事实上,如果您尝试从代码示例中删除 from os import *,您应该会发现问题已解决。
这个问题是一个人为的规范重复,用来解释发生了什么,即:为什么代码说from os import *时不一样?还有,这个问题怎么解决?
【问题讨论】:
标签: python file-io python-os shadowing