Trước tiên, bạn cần tạo thư mục.
Việc thực hiện mkdir -p
from this answer sẽ chỉ thực hiện những gì bạn muốn. mkdir -p
sẽ tạo bất kỳ thư mục cha nào theo yêu cầu và âm thầm không làm gì nếu nó đã tồn tại.
Ở đây tôi đã thực hiện một phương pháp safe_open_w()
trong đó kêu gọi mkdir_p
trên một phần thư mục của con đường, trước khi mở tập tin để viết:
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(...)
Nguồn
2014-05-21 21:21:00
Tôi đã sử dụng [đoạn này] (http://code.activestate.com/recipes/82465-a-friendly-mkdir/) trong nhiều năm và năm . – dabhaid