【问题标题】:Why do I get "TypeError: open() missing required argument 'flags' (pos 2)" or "TypeError: an integer is required (got type str)" when opening a file?为什么在打开文件时出现“TypeError: open() missing required argument \'flags\' (pos 2)\”或“TypeError: an integer is required (got type str)”?
【发布时间】: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


    【解决方案1】:

    使用像from os import *这样的星形导入——或者明确地使用from os import open,或者可能采取一些更间接的途径——意味着名称open将不再引用内置的open函数(也可以从io 标准库模块),而不是 os.open1个

    This function 也用于打开文件,但它提供了一个较低级别的接口。它提供了更多选项来控制文件的打开方式。

    特别是:此处的 flags 参数类似于内置 open 使用的 mode,但它提供了更多选项(其中大部分是特定于平台的)。它不是字符串,而应该是由某些标志值按位或运算生成的整数(即,它直接反映了 C 接口)。另一方面,mode 参数表示创建新文件时将使用的(类 UNIX 文件系统)权限,如果 open 应该创建一个。

    再次:正常代码不应该使用它,而是使用内置的open. (要在创建新文件后修复文件权限,请使用os.chmod。)

    为避免这种名称冲突,只需不要使用 star-imports 并且不要显式导入 open。相反,如果需要 os 标准库模块功能,只需 import 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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多