Python 将文件写入不存在的目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23793987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write file to a directory that doesn't exist
提问by Billz
How do I using with open() as f: ...
to write the file in a directory that doesn't exist.
我如何使用with open() as 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/
目录不存在。如果目录不存在,只需创建目录并将文件写入那里。
采纳答案by Jonathon Reinhart
You need to first create the directory.
您需要先创建目录。
The mkdir -p
implementation from this answerwill 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://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(...)
回答by huu
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))
回答by Alex Gidan
You can just createthe 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
来源:这个SO 解决方案
回答by Yakir Tsuberi
For Python 3 can use with pathlib.Path:
对于 Python 3 可以与pathlib.Path 一起使用:
from pathlib import Path
p = Path('Users' / 'bill' / 'output')
p.mkdir(exist_ok=True)
(p / 'output-text.txt').open('w').write(...)