Skip to content
Advertisement

easy way to convert windows paths with variables into python string

i tend to copy a lot of paths from a windows file explorer address bar, and they can get pretty long:

C:UsersavnavDocumentsDesktopSITESSERVERS4. server1_SERVER_MAKER

now let’s say i want to replace avnav with getpass.getuser().

if i try something like:

project_file = f'C:Users{getpass.getuser()}DocumentsDesktopSITESSERVERS4. server1_SERVER_MAKER'

i will get the following error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape

i presume it’s because of the single back slash – although would be cool to pinpoint exactly what part causes the error, because i’m not sure.

in any case, i can also do something like:

project_file = r'C:Users!!DocumentsDesktopSITESSERVERS4. server1_SERVER_MAKER'.replace('!!', getpass.getuser())

but this becomes annoying once i have more variables.

so is there a solution to this? or do i have to find and replace slashes or something?

Advertisement

Answer

Error


SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated UXXXXXXXX escape

Read carefully. Yes, the error is that. There’s a U char after a .

This, in Python, is the way to insert in a string a Unicode character. So the interpreter expects hex digits to be after U, but there’s none so there’s an exception raised.

Replace


so is there a solution to this? or do i have to find and replace slashes or something?

That is a possible solution, after replacing all with / everything should be fine, but that’s not the best solution.

Raw string


Have you ever heard of characters escaping? In this case is escaping {.

In order to prevent this, just put the path as a raw-string.

rf'C:Users{getpass.getuser()}DocumentsDesktopSITESSERVERS4. server1_SERVER_MAKER'
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement