14

In python 2.7 I was able to do:

file('text.txt', 'w').write('some text')

But in python 3 I have to use the open function, so I cannot write to a file on a single line anymore.

f = open('text.txt', 'w')
print('some text', file = f)
f.close()

Why did they remove the file function?

1 Answer 1

23
open('text.txt', 'w').write('some text')

works the same way and open has been the canonical way to open a file (and hence create a file instance) for a long time, even on Python 2.x.

It should be noted, though, that in Python 3.8+ this now generates a ResourceWarning about an unclosed file. This is because, although the file will typically be closed automatically after the write call, depending on garbage-collection settings this will not necessarily happen immediately, so the open file handle may persist. The proper way to ensure file closure and avoid the warning (and annoyingly, this makes the code no longer inline-able) is:

with open('text.txt', 'w') as fileHandle:
    fileHandle.write('some text')
Sign up to request clarification or add additional context in comments.

1 Comment

As a matter of fact, open has been preferred over file since Python 2.5 (source: docs.python.org/release/2.5/lib/built-in-funcs.html ). Python 2.5 was released in September, 2006. That's over eight years ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.