Python创建文件和目录

33

我在创建一个目录后,无法打开/创建/写入指定目录中的文件,原因不明。我正在使用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,它在某些情况下包含'/',这是造成问题的原因。

所以我需要处理'/'。 有没有办法转义'/'或者只能删除?


1
使用os.path.join()更好,将代码改为:os.path.join(path, img_alt+'.jpg') - Levon
@Ayos,请发布你正在使用的路径。 - Rob Cowie
жҲ‘дёҚжҳҺзҷҪpathгҖҒchap_pathе’Ңimg_altд№Ӣй—ҙзҡ„е…ізі»гҖӮ - tiwo
好观点 @tiwo 第二个代码片段似乎没有打开 path 目录中的文件。 - Rob Cowie
它并没有在目录路径中打开文件,而是在当前目录中打开。问题仍然存在。 - ffledgling
2个回答

91
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)数据。

针对 Edit 2 的回应,如果img_alt中有时包含"/":

img_alt = os.path.basename(img_alt)

1
我知道这是语法上正确的做法,但你能告诉我为什么会出现错误吗?为什么我们要使用“wb”而不是“w”? - ffledgling
2
如果无法到达要创建的目标目录(路径中最右边的目录),因为尚不存在父目录,则会引发OSError。 os.mkdir不是递归的,因此它不会沿着路径创建所有所需的目录。os.makedirs则可以实现递归创建。 - Rob Cowie
2
在处理文本和二进制文件时,'b' 在某些平台上具有特殊含义。引用文档中的话说,“在Windows上,Python区分文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动略微改变。” - tiwo
@RobCowie mkdir和makedirs在处理未转义空格时是否有不同的行为?这种行为与/usr/bin/mkdir有何不同?另外,请检查问题的更新部分。 - ffledgling
两者都可以正确处理未转义的空格。在shell中调用/usr/bin/mkdir需要您转义空格或引用路径字符串。关于中间目录,/usr/bin/mkdir默认情况下的行为类似于os.mkdir,并且如果使用-p参数调用,则类似于os.makedirs。 - Rob Cowie
1
除了mkdir -p在目录已经存在时会成功之外,Python 3.2还有os.makedirs(path, exist_ok=True),因此您不必调用os.path.exists,也没有竞争条件。 - Fred Foo

3
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 

请查看原始问题和被接受的答案,它明确指出 os.mkdir 不起作用,而被接受的答案指出应该使用 os.mkdirs - ffledgling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接