如果您的问题作为与此重复的问题而被关闭,那是因为您的代码如下:
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:需要一个整数(获取类型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 *
时会有所不同?另外,问题如何解决?
最佳答案
使用像 from os import *
这样的星号导入 - 或显式使用 from os import open
,或者可能采取一些更间接的路线 - 意味着名称 open
将不再引用内置的 open
函数(也可以从 io
标准库模块获取),而是引用 os .open
.1
This function也用于打开文件,但它提供了较低级别的接口(interface)。它提供了更多选项来控制文件的打开方式。
特别是:这里的 flags
参数类似于内置 open
使用的 mode
,但它提供了更多选项(其中大部分是特定于平台的)。它不是字符串,而是由某些标志值按位或产生的整数(即,它直接反射(reflect) C 接口(interface))。另一方面,mode
参数指示创建新文件时将使用的(类 UNIX 文件系统)权限(如果 open
应创建一个文件)。
再次强调:普通代码不应使用此函数,而应使用内置的open
。 (要在创建新文件后修复文件权限,请使用 os.chmod。)
为了避免这种名称冲突,只需不要使用星号导入,也不要显式导入open
。相反,如果需要 os
标准库模块功能,只需导入 os
,然后使用限定名称。
在解释器提示符下,del open
will get rid of the global binding of the name open
, making the builtin one visible again 。或者,由于内置 open
与内置 open
是相同的函数(不仅仅是另一个函数做同样的事情,而是实际上是同一个对象),我们可以重新导入该名称:from io import open
。这些技术也可以在from os import *
之后导入的脚本中使用,但它会更加干净并且不易出错从长远来看,只是为了避免明星进口。
1 请记住,名称一次只能指代一件事。另请参阅:Short description of the scoping rules?和 Why does code like `str = str(...)` cause a TypeError, but only the second time? .
关于python - 为什么我会得到 "TypeError: open() missing required argument ' 标志' (pos 2 )"or "TypeError : an integer is required (got type str)"when opening a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75514722/