'Converting windows paths to pathlib.WindowsPath() within a function in python

Edited for clarity

I need to be able to copy and paste a windows path directly from file explorer into a function which turns it into a pathlib.WindowsPath() object.

For example: what I want is something like.

def my_function(my_directory):
    my_directory = pathlib.WindowsPath(my_directory) #this is the important bit 
    files = [e for e in my_directory.itirdir()]
    return(files)

new_list = my_function('C:\Users\user.name\new_project\data')

print(new_list[0])

OUT[1] 'C:\\Users\\user.name\\new_project\\data\\data_set_1'

When I try this I get the error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (<string>, line 1)

Now I know that this is because of the \n in my string my windows path that I'm passing to the function, and that this will be fixed if i pass it in as r'C:\Users\user.name\new_project\data' but this isn't a practical solution to my issue. Is there a way I can fix this by converting the windows path to a raw string within my function?

I have tried:

def my_function(my_directory):
    input = fr'{my_directory}'# converting string to raw string
    path = pathlib.WindowsPath(input)
    files = [e for e in path.itirdir()]
    return(files)

new_list = my_function('C:\Users\user.name\new_project\data')

print(new_list[0]

OUT[1] 'C:\\Users\\user.name\\new_project\\data\\data_set_1'

but no joy.

Any help would be appreciated.



Solution 1:[1]

I solved this problem by using .encode('unicode escape')

for example:

from pathlib import Path

def input_to_path():
    user_input = input('Please copy and paste the folder address')
    user_input.encode('unicode escape')
    p = Path(user_input)
    return(p)

Solution 2:[2]

You can keep it simple by simply by converting it to a "raw" string. This can be used anywhere any other path can be used. (os.path, Pathlib, etc.)

mypath = r'C:\Users\user.name\new_project\data' print( 'mypath is =', mypath )

Output: path is = C:\Users\user.name\new_project\data

Solution 3:[3]

try this. Adding double backslash to dir so that python would not interpret single backslash as escape character

new_list = my_function('C:\\Users\\user.name\\new_project\\data')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hewey Dewey
Solution 3