Search code examples
pythonstringwindowspathlibrawstring

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

  • 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)