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?
"w" - Write - will create a file if the specified file does not 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With