33

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?

ffledgling
  • 11,502
  • 8
  • 47
  • 69

2 Answers2

90
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)
Rob Cowie
  • 22,259
  • 6
  • 62
  • 56
  • 1
    I understand this is the syntactically correct way of doing it, but can you actually tell me why the error occurs? And why are we using 'wb' instead of 'w' ? – ffledgling Jul 28 '12 at 11:35
  • 2
    The OSError is raised if the target dir to be created (the right-most directory in path) cannot be reached because a parent directory doesn't exist yet. os.mkdir is not recursive so it won't create all required directories along the path. os.makedirs does. – Rob Cowie Jul 28 '12 at 11:38
  • 2
    The 'b' is meaningful on platforms that behave different for text and binary files. To quote [the docs](http://docs.python.org/tutorial/inputoutput.html), "Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written." – tiwo Jul 28 '12 at 11:40
  • @RobCowie Do mkdir and makedirs behave differently to un-escaped spaces? And does this behaviour differ from /usr/bin/mkdir ? Also please check updated portion of the question. – ffledgling Jul 28 '12 at 11:45
  • Both handle unescaped spaces correctly. Invoking `/usr/bin/mkdir` in a shell requires you to escape spaces or quote the path string. With regard to intermediate dirs, /usr/bin/mkdir behaves like os.mkdir by default, and like os.makedirs if invoked with `-p` – Rob Cowie Jul 28 '12 at 11:51
  • 1
    ... except that `mkdir -p` succeeds when the directory already exists. Python 3.2 has `os.makedirs(path, exist_ok=True)`, so you don't have to call `os.path.exists` and there's no race condition. – Fred Foo Jul 28 '12 at 12:20
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 
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Surya
  • 84
  • 5
  • Please see the original question and the accepted answer, it explicitly said that `os.mkdir` did not work, and the accepted answer pointed out that `os.mkdirs` was to be used. – ffledgling Aug 31 '17 at 20:04