通过Python创建文件和目录 [英] Creating files and directories via Python

查看:228
本文介绍了通过Python创建文件和目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法创建目录,然后打开/创建/写入指定目录中的文件。原因似乎不清楚我。我使用os.mkdir()和

  path = chap_name 
打印路径:+ chap_path #For调试目的
如果不是os.path.exists(路径):
os.mkdir(路径)
temp_file = open(path +'/'+ img_alt +'。jpg','w'
temp_file.write(buff)
temp_file.close()
打印...完成

我收到错误

 OSError:[Errno 2]没有这样的文件或目录:'Some Path Name' pre> 

路径的格式为具有未转义空格的文件夹名称



我做错了什么这里?






更新:我尝试运行代码而不创建目录

  path = chap_name 
打印路径:+ chap_path#用于调试目的
temp_file = open(img_alt +'。jpg','w')
temp_file.write(buff)
temp_file.close()
打印...完成

仍然收到错误。更困难了。






更新2:问题似乎是img_alt,在某些情况下它包含/这导致麻烦。



所以我需要处理'/'。
有没有逃避'/'或删除唯一的选项?

解决方案

  import os 

path = chap_name

如果不是os.path.exists(路径):
os.makedirs(路径)

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)


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)

这篇关于通过Python创建文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆