“ file”在 python 中是关键字吗?

在 python 中 file是关键字吗?

我已经看到一些代码使用关键字 file只是罚款,而其他人建议不要使用它,我的编辑器是彩色编码作为一个关键字。

32376 次浏览

No, file is not a keyword:

>>> import keyword
>>> keyword.iskeyword('file')
False

The name is not present in Python 3. In Python 2, file is a built-in:

>>> import __builtin__, sys
>>> hasattr(__builtin__, 'file')
True
>>> sys.version_info[:2]
(2, 7)

It can be seen as an alias for open(), but it was removed in Python 3, where the new io framework replaced it. Technically, it is the type of object returned by the Python 2 open() function.

file is neither a keyword nor a builtin in Python 3.

>>> import keyword
>>> 'file' in keyword.kwlist
False
>>> import builtins
>>> 'file' in dir(builtins)
False

file is also used as variable example from Python 3 doc.

with open('spam.txt', 'w') as file:
file.write('Spam and eggs!')