Python中的'file'是关键字吗?

109

file 是 Python 中的一个关键字吗?

我看到一些代码可以正常使用 file 关键字,而有些人建议不要使用它,并且我的编辑器将其显示为关键字。


3
好的,以下是Python 2官方文档中内置函数的链接翻译:https://docs.python.org/zh-cn/2/library/functions.html - BartoszKP
2
-1 当试图学习一门语言时,寻找该语言的关键词列表既是必要的,也是自然的。 - Solkar
9
你是指哪个版本的Python?Python2还是Python3?在我看来,提问者的困惑是合理的。 - zero2cx
3个回答

148

不,file 不是一个关键字:

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

在Python 3中不存在这个名称。在Python 2中,file是一个内置函数:

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

它可以被看作是open()的别名,但在Python 3中被移除,新的io框架取代了它。从技术上讲,它是Python 2 open()函数返回的对象类型。

27
如果我只打算支持Python 3,那么使用file作为变量名是否可以? - Gustavo Bezerra
28
当然可以! @GustavoBezerra 绝对没问题! - Martijn Pieters

24

file 不是 Python 3 中的关键字或内置函数。

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

file也是Python 3文档中的变量示例。

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

2
如其他人建议的一样,在 Python 3 中,type 默认情况下被定义:
Python 3.8.10 (default, Nov 14 2022, 12:59:47) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined

在VS Code和可能的其他编辑器中,颜色编码可能是指Python 2,其中默认定义了它,它是由open()返回的类型:

Python 2.7.18 (default, Jul  1 2022, 12:27:04) 
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> file
<type 'file'>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接