如果目录和文件名尚不存在,则立即创建它们

时间:2015-06-08 19:34:37

标签: python

如果它还不存在,我正试图一次创建完整路径,但我不确定它是否可行。这是我现在的代码:

absolute_path = '/home/{signup_code}/{resource}/process'
missing_file = absolute_path.format(resource='agents', signup_code=signup_code)
with open(missing_file, 'a') as f:
    f.write(listing_kwargs['agent_id'] + "\n")

这就是我得到的错误:

FileNotFoundError: [Errno 2] No such file or directory: '/home/ith/agents/process'

或者我必须做这样的事情:

path = '/home/{signup_code}/{resource}/'
os.makedirs(path, exist_ok=True)

process = os.path.join(path, 'process')

with open(process, 'a') as f:
    f.write(listing_kwargs['agent_id'] + "\n")

1 个答案:

答案 0 :(得分:1)

没有办法直接这样做。您需要将其分解为两部分。首先,使用os.makedirs()创建路径,然后打开该文件。好处是你可以将这个过程包装在一个函数中,这样它很容易重复:

import os
from contextlib import contextmanager

@contextmanager
def open_with_create_path(fname, file_mode='r', buffering=-1,
                          encoding=None, errors=None, newline=None,
                          dir_mode=0o777, exist_ok=True):
    os.makedirs(os.path.dirname(fname), mode=dir_mode, exist_ok=exist_ok)
    f = open(fname, mode=file_mode, buffering=buffering, encoding=encoding,
             errors=errors, newline=newline)
    try:
        yield f
    finally:
        f.close()

FNAME = r'C:\temp\foo\bar\baz.txt'
with open_with_create_path(FNAME, 'w') as f:
    print('foo', file=f)