83
votes

Is file a keyword in python?

I've seen some code using the keyword file just fine, while others have suggested not to use it and my editor is color coding it as a keyword.

2
-1 searching for a list of keywords of a language is both mandatory and natural when trying to learn that language. - Solkar
@Solkar To which language do you refer? Python2 or Python3? The confusion of OP is reasonable, imo. - zero2cx

2 Answers

102
votes

No, file is a builtin, not a keyword:

>>> import keyword
>>> keyword.iskeyword('file')
False
>>> import __builtin__
>>> hasattr(__builtin__, 'file')
True

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

3
votes

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!')