-3

I would like to create an empty file in Python. But I have difficulty creating one..Below is the Python code I used to create but it gives me error:

gdsfile  = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
    os.system(touch gdsfile)

Error I got: File "/home/hha/bin/test.py", line 29 os.system(touch gdsfile) ^ SyntaxError: invalid syntax

But from the command line, I am able to create new file using: touch

Thank you very much for your help Howard

howard
  • 51
  • 2
  • 2
  • 3
  • 3
    The argument to `os.system` needs to be a string. That's not what you're passing right now. Also, there's no reason to call out to the `touch` command when you could just use Python's own `open` method. – larsks Mar 28 '17 at 23:49

1 Answers1

8

First you have a syntax error because os.system() expects a string argument and you have not provided one. This will fix your code:

os.system('touch {}'.format(gdsfile))

which constructs a string and passes it to os.system().

But a better way (in Python >= 3.3) is to simply open the file using the open() builtin:

gdsfile  = "/home/hha/temp.gds"
try:
   open(gdsfile, 'x')
except FileExistsError:
   pass

This specifies mode x which means exclusive creation - the operation will fail if the file already exists, but create it if it does not.

This is safer than using os.path.isfile() followed by open() because it avoids the potential race condition where the file might be created by another process in between the check and the create.


If you are using Python 2, or an earlier version of Python 3, you can use os.open() to open the file with the exclusive flag.

import os
import errno

gdsfile  = "/home/hha/temp.gds"
try:
    os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • I suggest adding the 'with' in front of the 'open', so that it will automatically clean up the returned file handle, e.g. ' with open(gdsfile, 'x') as touched_file: pass' – Gino Oct 01 '17 at 14:23
  • ``` with open(file_name, 'a') as f: pass ``` – vishal Sep 11 '19 at 10:39