I\'m trying to open a file, and if the file doesn\'t exist, I need to create it and open it for writing. I have this so far:
#open file for reading
fn = input(\"
Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.
import os
with open("file.txt", 'w+') as f:
f.write("file is opened for business")
Using input()
implies Python 3, recent Python 3 versions have made the IOError
exception deprecated (it is now an alias for OSError
). So assuming you are using Python 3.3 or later:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except FileNotFoundError:
file = open(fn, 'w')
If you don't need atomicity you can use os module:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
UPDATE:
As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()
import os
if not os.path.exists('/tmp/test'):
with open('/tmp/test', 'w'): pass