通过 Python 创建文件和目录 [英] Creating files and directories via Python
问题描述
我在创建目录然后打开/创建/写入指定目录中的文件时遇到问题.原因对我来说似乎不清楚.我正在使用 os.mkdir() 和
I'm having trouble creating a directory and then opening/creating/writing into a file in the specified directory. The reason seems unclear to me. I'm using os.mkdir() and
path=chap_name
print "Path : "+chap_path #For debugging purposes
if not os.path.exists(path):
os.mkdir(path)
temp_file=open(path+'/'+img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"
我收到错误
OSError: [Errno 2] No such file or directory: 'Some Path Name'
路径的格式为带有未转义空格的文件夹名称"
Path is of the form 'Folder Name with un-escaped spaces'
我在这里做错了什么?
更新:我尝试在不创建目录的情况下运行代码
Update: I tried running the code without creating the directory
path=chap_name
print "Path : "+chap_path #For debugging purposes
temp_file=open(img_alt+'.jpg','w')
temp_file.write(buff)
temp_file.close()
print " ... Done"
仍然出现错误.更糊涂了.
Still get an error. Confused further.
更新2:问题似乎是img_alt,它在某些情况下包含'/',这导致了问题.
Update 2:The Problem seems to be the img_alt, it contains a '/' in some cases, which makes is causing the trouble.
所以我需要处理'/'.无论如何要转义/"还是删除是唯一的选择?
So I need to handle the '/'. Is there anyway to escape the '/' or is deletion the only option?
推荐答案
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)
关键是使用os.makedirs
代替os.mkdir
.它是递归的,即它生成所有中间目录.见 http://docs.python.org/library/os.html
Key point is to use os.makedirs
in place of os.mkdir
. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
在存储二进制 (jpeg) 数据时以二进制模式打开文件.
Open the file in binary mode as you are storing binary (jpeg) data.
响应编辑 2,如果 img_alt 有时包含/":
In response to Edit 2, if img_alt sometimes has '/' in it:
img_alt = os.path.basename(img_alt)
这篇关于通过 Python 创建文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!