Reputation: 648
i tend to copy a lot of paths from a windows file explorer address bar, and they can get pretty long:
C:\Users\avnav\Documents\Desktop\SITES\SERVERS\4. server1\0_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()}\Documents\Desktop\SITES\SERVERS\4. server1\0_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\!!\Documents\Desktop\SITES\SERVERS\4. server1\0_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?
Upvotes: 2
Views: 1256
Reputation: 1
I made a piece of code to convert File Explorer file path into a python file format:
rawpath = input("PATH: ")
ds = "\\"
def CF(path):
if ds in path:
path = rawpath.replace("\\", "\\\"")
rpath = repr(path).replace("\"", "")
print(rpath)
CF(rawpath)
Upvotes: 0
Reputation: 4088
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 U
nicode character. So the interpreter expects hex
digits to be after \U
, but there's none so there's an exception raised.
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()}\Documents\Desktop\SITES\SERVERS\4. server1\0_SERVER_MAKER'
Upvotes: 3