Reputation: 499
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?
Upvotes: 14
Views: 14954
Reputation: 15349
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')
Upvotes: 23