python创建目录和文件,通过Python创建文件和目录

博主在使用Python处理包含空格和斜杠的文件路径时遇到错误,通过os.makedirs()和os.path.join()解决了路径创建和文件写入问题。关键在于用os.makedirs()替换os.mkdir(),确保目录递归创建。建议处理斜杠和特殊字符,如将'/’转为os.path.basename()。
摘要由CSDN通过智能技术生成

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"

I get the error

OSError: [Errno 2] No such file or directory: 'Some Path Name'

Path is of the form 'Folder Name with un-escaped spaces'

What am I doing wrong here?

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.

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)

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

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值