擅长:python、mysql、java
<pre><code>import os
path = chap_name
if not os.path.exists(path):
os.makedirs(path)
filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
temp_file.write(buff)
</code></pre>
<p>关键是用<code>os.makedirs</code>代替<code>os.mkdir</code>。它是递归的,即它生成所有中间目录。见<a href="http://docs.python.org/library/os.html">http://docs.python.org/library/os.html</a></p>
<p>在存储二进制(jpeg)数据时以二进制模式打开文件。</p>
<p>针对编辑2,如果img_alt中有时包含“/”,则:</p>
<pre><code>img_alt = os.path.basename(img_alt)
</code></pre>