Write file to a directory that doesn't exist

后端 未结 4 1451
[愿得一人]
[愿得一人] 2020-12-14 02:35

How do I using with open() as f: ... to write the file in a directory that doesn\'t exist.

For example:



        
相关标签:
4条回答
  • 2020-12-14 02:59

    You can just create the path you want to create the file using os.makedirs:

    import os
    import errno
    
    def make_dir(path):
        try:
            os.makedirs(path, exist_ok=True)  # Python>3.2
        except TypeError:
            try:
                os.makedirs(path)
            except OSError as exc: # Python >2.5
                if exc.errno == errno.EEXIST and os.path.isdir(path):
                    pass
                else: raise
    

    Source: this SO solution

    0 讨论(0)
  • 2020-12-14 03:01

    You need to first create the directory.

    The mkdir -p implementation from this answer will do just what you want. mkdir -p will create any parent directories as required, and silently do nothing if it already exists.

    Here I've implemented a safe_open_w() method which calls mkdir_p on the directory part of the path, before opening the file for writing:

    import os, os.path
    import errno
    
    # Taken from https://stackoverflow.com/a/600612/119527
    def mkdir_p(path):
        try:
            os.makedirs(path)
        except OSError as exc: # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else: raise
    
    def safe_open_w(path):
        ''' Open "path" for writing, creating any parent directories as needed.
        '''
        mkdir_p(os.path.dirname(path))
        return open(path, 'w')
    
    with safe_open_w('/Users/bill/output/output-text.txt') as f:
        f.write(...)
    
    0 讨论(0)
  • 2020-12-14 03:02

    For Python 3 can use with pathlib.Path:

    from pathlib import Path
    
    p = Path('Users' / 'bill' / 'output')
    p.mkdir(exist_ok=True)
    (p / 'output-text.txt').open('w').write(...)
    
    0 讨论(0)
  • 2020-12-14 03:10

    Make liberal use of the os module:

    import os
    
    if not os.path.isdir('/Users/bill/output'):
        os.mkdir('/Users/bill/output')
    
    with open('/Users/bill/output/output-text.txt', 'w') as file_to_write:
        file_to_write.write("{}\n".format(result))
    
    0 讨论(0)
提交回复
热议问题