Python Forum

Full Version: Python Directory and File Create Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to create a Directory (or say, Folder) under the "/tmp/" path.

There, I want to create a Writable Binary file and dump some data. I was doing that in the following way, but neither the Directory nor the File is getting created.
...
fnamehead,fnametail=os.path.split(name) #'name' contains a arbitrary filepath
fname='/tmp/'+fnametail
os.makedirs(os.path.dirname(fname))

with open ('xyz','ab') as fd:
	fd.write(data)
...
Please help me with that.
From your code os.path.dirname(fname) will always return '/tmp'. So effectively you always try to create '/tmp' if it does not exists.

import os

fnametail = 'somefolder'
fname='/tmp/'+fnametail
print(os.path.dirname(fname))
Output:
/tmp
And because you don't specify path, 'xyz' file is created in current working directory (i.e. the one from which you run your code)

As a side note - use os.path.join() to construct paths, not concatenation