Reputation:
I am trying to join an absolute path and variable folder path depending on the variable run
. However when I use the following code it inserts a forward slash after a string, which I don't require. How can I remove the slash after Folder_
?
import os
currentwd = os.getcwd()
folder = '001'
run_folder = os.path.join(currentwd, 'Folder_', folder)
print run_folder
The output I get using this code is:
/home/xkr/Workspace/Folder_/001
Upvotes: 1
Views: 3077
Reputation: 1124758
You are asking os.path.join()
to take multiple path elements and join them. It is doing its job.
Don't use os.path.join()
to produce filenames; just use concatenation:
run_folder = os.path.join(currentwd, 'Folder_' + folder)
or use string formatting; the latter can give you such nice features such as automatic padding of integers:
folder = 1
run_folder = os.path.join(currentwd, 'Folder_{:03d}'.format(folder))
That way you can increment folder
past 10 or 100 and still have the correct number of leading zeros.
Note that you don't have to use os.getcwd()
; you could also use os.path.abspath()
, it'll make relative paths absolute based on the current working directory:
run_folder = os.path.abspath('Folder_' + folder)
Upvotes: 3