Python Forum
Python Directory and File Create Error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Directory and File Create Error
#1
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.
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create Choices from .ods file columns cspower 3 520 Dec-28-2023, 09:59 PM
Last Post: deanhystad
  Recommended way to read/create PDF file? Winfried 3 2,786 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  Use PM4PY and create working file thomaskissas33 0 573 Nov-14-2023, 06:53 AM
Last Post: thomaskissas33
  Create csv file with 4 columns for process mining thomaskissas33 3 695 Nov-06-2023, 09:36 PM
Last Post: deanhystad
  Coding error. Can't open directory EddieG 6 1,063 Jul-13-2023, 06:47 PM
Last Post: deanhystad
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,085 Jun-27-2023, 01:17 PM
Last Post: diver999
  create a default path with idle to a specific directory greybill 0 846 Apr-23-2023, 04:32 AM
Last Post: greybill
  create exe file for linux? korenron 2 911 Mar-22-2023, 01:42 PM
Last Post: korenron
  Extract file only (without a directory it is in) from ZIPIP tester_V 1 928 Jan-23-2023, 04:56 AM
Last Post: deanhystad
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,071 Dec-15-2022, 04:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020