Python Forum
Python Directory and File Create Error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python Directory and File Create Error (/thread-14768.html)



Python Directory and File Create Error - basic_learner - Dec-16-2018

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.


RE: Python Directory and File Create Error - buran - Dec-16-2018

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