通过Python创建文件和目录

2024-03-29 08:33:25 发布

您现在位置: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,在某些情况下它包含一个“/”,这使得正在引发问题。

所以我需要处理“/”。 是否仍有转义“/”或删除是唯一的选项?


Tags: pathname目录imgforosalttemp
2条回答
    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 
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

在存储二进制(jpeg)数据时以二进制模式打开文件。

针对编辑2,如果img_alt中有时包含“/”,则:

img_alt = os.path.basename(img_alt)

相关问题 更多 >