![]() |
File path by adding various variables - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: File path by adding various variables (/thread-39882.html) |
File path by adding various variables - Mishal0488 - Apr-28-2023 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) RE: File path by adding various variables - snippsat - Apr-28-2023 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.STDSo 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 RE: File path by adding various variables - deanhystad - Apr-28-2023 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 worksAmong 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/" |