Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file path from variables

Tags:

python

path

I am looking for some advice as to the best way to generate a file path using variables, currently my code looks similar to the following:

path = /my/root/directory for x in list_of_vars:         if os.path.isdir(path + '/' + x):  # line A             print(x + ' exists.')         else:             os.mkdir(path + '/' + x)       # line B             print(x + ' created.') 

For lines A and B as shown above, is there a better way to create a file path as this will become longer the deeper I delve into the directory tree?

I envisage an existing built-in method to be used as follows:

create_path(path, 'in', 'here') 

producing a path of the form /my/root/directory/in/here

If there is no built in function I will just write myself one.

Thank you for any input.

like image 264
Thorsley Avatar asked Sep 20 '10 13:09

Thorsley


People also ask

How do you create a file path?

If you're using Windows 11, simply right-click on it. Then, select “Copy as path” in the contextual menu. Alternatively, in Windows 10, you can also select the item (file, folder, library) and click or tap on the “Copy as path” button from File Explorer's Home tab in Windows 10.

How do you create a file path in Python?

You can use the os. mkdir("path/to/dir/here") function to create a directory in Python. This function is helpful if you need to create a new directory that doesn't already exist.

How do you add a file path to a file?

From the "Text" group, click [Quick Parts] > Select "Field..." Under "Field names," select "FileName." In the "Field properties" section, select a format. In the "Field options" section, check "Add path to filename." The file name will now appear in the header or footer.


2 Answers

You want the path.join() function from os.path.

>>> from os import path >>> path.join('foo', 'bar') 'foo/bar' 

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory' final_path = os.join(start_path, *list_of_vars) if not os.path.isdir(final_path):     os.makedirs (final_path) 
like image 22
nmichaels Avatar answered Sep 21 '22 12:09

nmichaels


Yes there is such a built-in function: os.path.join.

>>> import os.path >>> os.path.join('/my/root/directory', 'in', 'here') '/my/root/directory/in/here' 
like image 172
kennytm Avatar answered Sep 22 '22 12:09

kennytm