Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
Miguel Hernandez Avatar asked Mar 04 '16 22:03

Miguel Hernandez


People also ask

Which mode create a new file if file does not exist?

"w" - Write - will create a file if the specified file does not exist.

Does append create a file if it doesn't exist?

Create file if it does not exist by Using append modeIf the file does not exist, it creates a new file for reading and writing. It will not truncate the file and append the content at end of the file as shown in the example below.

Does StreamWriter create file if not exist?

C# StreamWriter append text This constructor initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, the constructor creates a new file.


1 Answers

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 
like image 149
Kron Avatar answered Sep 21 '22 13:09

Kron