Create a file if it doesn't exist
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("Enter file to open: ")
fh = open(fn,'r')
# if file does not exist, create it
if (!fh)
fh = open ( fh, "w")
The error message says there's an issue on the line if(!fh)
. Can I use exist
like in Perl?
Solution 1:
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
Solution 2:
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in (over)write mode
[it overwrites the file if it already exists]
r+ open an existing file in read+write mode
a+ create file if it doesn't exist and open it in append mode
'''
example:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]
Solution 3:
Well, first of all, in Python there is no !
operator, that'd be not
. But open
would not fail silently either - it would throw an exception. And the blocks need to be indented properly - Python uses whitespace to indicate block containment.
Thus we get:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except IOError:
file = open(fn, 'w')
Solution 4:
Here's a quick two-liner that I use to quickly create a file if it doesn't exists.
if not os.path.exists(filename):
open(filename, 'w').close()