我需要写一个文件(截断),它本身的路径可能不存在)。例如,我想写/tmp/a/b/c/config
,但/tmp/a
本身可能不存在。然后,open('/tmp/a/b/c/config', 'w')
显然不起作用,因为它没有创建必要的目录。但是,我可以使用以下代码:
import os
config_value = 'Foo=Bar' # Temporary placeholder
config_dir = '/tmp/a/b/c' # Temporary placeholder
config_file_path = os.path.join(config_dir, 'config')
if not os.path.exists(config_dir):
os.makedirs(config_dir)
with open(config_file_path, 'w') as f:
f.write(config_value)
有更多的Pythonic方法吗? Python 2.x和Python 3.x都很高兴知道(即使我在代码中使用2.x,由于依赖性原因)。
答案 0 :(得分:2)
如果您在多个地方重复此模式,您可以创建自己的上下文管理器,扩展lastrow1 = Sheets("ResourcesLib").Range("A" & Rows.Count).End(xlUp).row
For i = 1 To lastrow1
resources = Sheets("ResourcesLib").Cells(i, "A").Value
Sheets("sheet3").Activate
lastrow2 = Sheets("sheet3").Range("B" & Rows.Count).End(xlUp).row
For j = 2 To lastrow2
If Sheets("sheet3").Cells(j, "B").Value = resources Then
Sheets("ResourcesLib").Activate
NoCell = rsrcl.Cells(i, rsrcl.Columns.Count).End(xlToLeft).Column
rsrcl.Range(rsrcl.Cells(i, 2), rsrcl.Cells(i,rsrcl.Cells(i,Columns.Count).End(xlToLeft).Column)).Copy
rsrca.Range("D" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Sheets("sheet3").Activate
Sheets("sheet3").Cells(j, "A").Copy
rsrca.Range(Cells(k, 1), Cells(m + (NoCell - 1), 1)).PasteSpecial
Sheets("sheet3").Cells(j, "B").Copy
rsrca.Range(Cells(k, 2), Cells(m + (NoCell - 1), 2)).PasteSpecial
Sheets("sheet3").Cells(j, "C").Copy
rsrca.Range(Cells(k, 3), Cells(m + (NoCell - 1), 3)).PasteSpecial
End If
Next j
k = (NoCell - 2) + k
m = k
Application.CutCopyMode = False
Next i
并重载open()
:
__enter__()
然后您的代码变为:
import os
class OpenCreateDirs(open):
def __enter__(self, filename, *args, **kwargs):
file_dir = os.path.dirname(filename)
if not os.path.exists(file_dir):
os.makedirs(file_dir)
super(OpenCreateDirs, self).__enter__(filename, *args, **kwargs)
运行import os
config_value = 'Foo=Bar' # Temporary placeholder
config_file_path = os.path.join('/tmp/a/b/c', 'config')
with OpenCreateDirs(config_file_path, 'w') as f:
f.write(config_value)
时要调用的第一个方法是with open(...) as f:
。因此,通过在调用open.__enter__()
之前创建目录,可以在尝试打开文件之前创建目录。