Python Forum

Full Version: File path by adding various variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Guys

This may be a really simple issue which has stumped me.
The "FPath" variable has two back slashes at the end.
In the current setup the code will run, however with the double backslash the file path is invalid.
Using one backslash at the end does not work as errors are developed

The "FName" variable will be defined from a spreadsheet, however below I have just assigned it a name for the sake of this post.

How can I set up the code so that the file path will be valid?


FPath = r"C:\Users\mishal.mohanlal\Desktop\\"
FName = "Structure1.STD"
F = FPath+FName
print(F)
Should not use double backslash(last) when use raw string,should be nothing.
If use pathlib then it dos not matter it will fix it.
>>> import pathlib
>>> 
>>> FPath = r"C:\Users\mishal.mohanlal\Desktop\\"
>>> FPath
'C:\\Users\\mishal.mohanlal\\Desktop\\\\'
>>> FName = "Structure1.STD"
>>> file_path = pathlib.PurePath(FPath, FName)
>>> file_path
PureWindowsPath('C:/Users/mishal.mohanlal/Desktop/Structure1.STD')
>>> print(file_path)
C:\Users\mishal.mohanlal\Desktop\Structure1.STD
So this is a new and better of doing what os did before with os.path.join()
Example
>>> import os
>>> 
>>> FPath = r"C:\Users\mishal.mohanlal\Desktop"
>>> FName = "Structure1.STD"
>>> os.path.join(FPath, FName)
'C:\\Users\\mishal.mohanlal\\Desktop\\Structure1.STD'
So this way will not fix the double backslash usage as pathlib dos,so here i use without.
Of course both work in pathlib.
>>> import pathlib
>>> 
>>> FPath = r"C:\Users\mishal.mohanlal\Desktop"
>>> FName = "Structure1.STD"
>>> file_path = pathlib.PurePath(FPath, FName)
>>> file_path
PureWindowsPath('C:/Users/mishal.mohanlal/Desktop/Structure1.STD')
>>> print(file_path)
C:\Users\mishal.mohanlal\Desktop\Structure1.STD
You are not allowed to end a string literal with an odd number of backslashes. It doesn't matter if the string is raw or not. So if you need a single backslash at the end of a string, you cannot use a raw string.
FPath = "C:\\Users\\mishal.mohanlal\\Desktop\\"   # this works
Among the other options mentioned (I like pathlib the best), you can also use forward slashes. This will work as a file path in windows even though windows uses backslashes in file paths. Python fixes the separator when opening a file. It addition to avoiding the escape sequence nightmare, this lets you write code that runs on windows an linux.
FPath = "C:/Users/mishal.mohanlal/Desktop/"