Write file to a directory that doesn't exist
如何使用
例如:
1 2 3 | with open('/Users/bill/output/output-text.txt', 'w') as file_to_write: file_to_write.write("{} ".format(result)) |
假设
您需要首先创建目录。
这个答案中的
在这里,我实现了一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(...) |
充分利用
1 2 3 4 5 6 7 8 | 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("{} ".format(result)) |
您只需使用os.makedirs创建要创建文件的路径:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
资料来源:这个解决方案