Python:写入文件到目录不存在

时间:2021-11-20 13:19:38

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

如何使用open()作为f:…要在不存在的目录中写入文件。

For example:

例如:

with open('/Users/bill/output/output-text.txt', 'w') as file_to_write:
    file_to_write.write("{}\n".format(result))

Let's say the /Users/bill/output/ directory doesn't exist. If the directory doesn't exist just create the directory and write the file there.

假设/Users/bill/output/目录不存在。如果目录不存在,只需创建目录并在那里写入文件。

3 个解决方案

#1


21  

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.

这个答案中的mkdir -p实现将执行您想要的操作。mkdir -p将根据需要创建任何父目录,如果已经存在,则静默不做任何操作。

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:

在这里,我实现了一个safe_open_w()方法,它在路径的目录部分调用mkdir_p,然后打开文件进行写入:

import os, os.path
import errno

# Taken from https://*.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(...)

#2


7  

Make liberal use of the os module:

*使用os模块:

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))

#3


0  

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

您可以使用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

来源:这样的解决方案

#1


21  

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.

这个答案中的mkdir -p实现将执行您想要的操作。mkdir -p将根据需要创建任何父目录,如果已经存在,则静默不做任何操作。

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:

在这里,我实现了一个safe_open_w()方法,它在路径的目录部分调用mkdir_p,然后打开文件进行写入:

import os, os.path
import errno

# Taken from https://*.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(...)

#2


7  

Make liberal use of the os module:

*使用os模块:

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))

#3


0  

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

您可以使用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

来源:这样的解决方案