Creating A Missing Directory / File Structure - Python
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 g
Solution 1:
def createAndOpen(filename, mode):
os.makedirs(os.path.dirname(path), exist_ok=True)
returnopen(filename, mode)
Now, you can open the file and create the folder at once:
withcreateAndOpen('/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.
Post a Comment for "Creating A Missing Directory / File Structure - Python"