通过Python创建文件和目录

13 浏览
0 Comments

通过Python创建文件和目录

我在创建一个目录然后打开/创建/写入指定目录中的文件时遇到了问题。原因对我来说不太清楚。我正在使用os.mkdir()和

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=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"

仍然出现错误。更加困惑。


更新2:问题似乎在于img_alt,它在某些情况下包含一个'/',这导致了问题。

所以我需要处理'/'。

有没有办法转义'/',还是删除是唯一的选项?

0