3

I'm writing a function that does some operations with a .log file: The program checks if /logs/ansible.log exists before proceeding. If /logs/ansible.log doesn't exist, it should go ahead and create the file / directory structure (both don't exist prior).

try:
  if not os.path.exists("/logs/ansible.log"):
     # create the /logs/ansible.log file
finally:
  # do something

I know I can create the ansible.log file with open('ansible.log', 'w') and create the directory with os.makedirs('/logs/'), however how can I simply create '/logs/ansible.log' at once?

*** Assume program is being executed as root

cybertextron
  • 10,547
  • 28
  • 104
  • 208
  • 1
    `os.makedirs('/logs')` See http://stackoverflow.com/questions/273192/in-python-check-if-a-directory-exists-and-create-it-if-necessary – fiacre Jun 01 '15 at 20:01
  • 1
    @fiacre I already know that ... I want to create `/logs/ansible.log` at once ... see how I referred to that in the question – cybertextron Jun 01 '15 at 20:03
  • python or not, the OS will not create all at once... – Sylvain Biehler Jun 01 '15 at 20:07
  • 1
    But, that is not possible in shell -- if /logs does not exists you can't create /logs/ansible.log with a single command. As with shell, in python you have to create directory first *then* create the file. – fiacre Jun 01 '15 at 20:07

1 Answers1

6
def createAndOpen(filename, mode):
     os.makedirs(os.path.dirname(path), exist_ok=True)
     return open(filename, mode)

Now, you can open the file and create the folder at once:

with createAndOpen('/logs/ansible.log', 'a') as f:
    f.write('Hello world')

Otherwise, this isn’t possible. The operating system does not give you a single function that does this, so whatever else existed that does this would have to have a similar logic as above. Just less visible to you. But since it simply doesn’t exist, you can just create it yourself.

poke
  • 369,085
  • 72
  • 557
  • 602