Create a file if it doesn't exist

Viewed 325198

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?

9 Answers

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()

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'.

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

If you know the folder location and the filename is the only unknown thing,

open(f"{path_to_the_file}/{file_name}", "w+")

if the folder location is also unknown

try using

pathlib.Path.mkdir
Related