I'm trying to build a path in Python (windows) and frustratingly enough it gives me wrong path every time. The path I'm trying to build is C:\Users\abc\Downloads\directory\[log file name].
So when I use print(os.getcwd()) it returns C:\Users\abc\Downloads\directory which is fine. But when I try to use the os join in python, (os.path.join(os.path.abspath(os.getcwd()),GetServiceConfigData.getConfigData('logfilepath')))
it returns only C:\Logs\LogMain.log and not the desired output. (Path.cwd().joinpath(GetServiceConfigData.getConfigData('logfilepath'))) also returns the same result.
logfilepath is an XML string <add key="logfilepath" value="\Logs\LogMain.log" />
2 Answers 2
Thanks for all the help, in the end it was solved by removing 1 backslash.
<add key="logfilepath" value="\Logs\LogMain.log" />
to
<add key="logfilepath" value="Logs\LogMain.log" />
Comments
Your logfilepath is \Logs\LogMain.log and this is absolute path (without drive), not relative path, and not only filename - so it will not join as you expect.
When you try to join absolute path then it keeps only drive and replaces previous absolute path.
You have to get only filename from \Logs\LogMain.log - ie.
logfilepath.split('\\')[-1]
to have only LogMain.log and finally get
C:\Users\abc\Downloads\directory\LogMain.log
folder = os.path.abspath(os.getcwd())
logfilepath = GetServiceConfigData.getConfigData('logfilepath')
filename = logfilepath.split('\\')[-1]
os.path.join(folder, filename)
EDIT
If logfilepath is object pathlib.Path like
from pathlib import Path
p = Path('\Logs\LogMain.log')
then you may get only filename using
p.name
print(os.getcwd())works, butos.path.join(os.path.abspath(os.getcwd()),GetServiceConfigData.getConfigData('logfilepath'))doesn't - try deletingos.path.abspathin the not-working line. And tryprint(os.path.abspath(os.getcwd())).os.path.join(os.getcwd(),GetServiceConfigData.getConfigData('logfilepath'))->C:\Logs\LogMain.logPath.cwd().joinpath(GetServiceConfigData.getConfigData('logfilepath'))-> C:\Logs\LogMain.logos.path.abspath(os.getcwd())-> C:\Users\xxxx\Downloads\directoryprint(os.path.join("C:\Users\xxxx\Downloads\directory", "LogMain.log"), os.path.join(os.path.abspath("C:\Users\xxxx\Downloads\directory"), "LogMain.log")?GetServiceConfigData.getConfigData('logfilepath')- if it givesC:\Logs\LogMain.logor\Logs\LogMain.logthen it is absolut path and it will notjoinwith other folder. You would have to remobe starting \ from\Logs\LogMain.logto get relative pathLogs\LogMain.logand then it willjoinwith other folder. OR you should get only filename from\Logs\LogMain.logusing ie,split('\')[-1]