Jamalan
Jamalan

Reputation: 580

Python Pathlib escaping string stored in variable

I'm on windows and have an api response that includes a key value pair like

object = {'path':'/my_directory/my_subdirectory/file.txt'}

I'm trying to use pathlib to open and create that structure relative to the current working directory as well as a user supplied directory name in the current working directory like this:

output = "output_location"
path = pathlib.Path.cwd().joinpath(output,object['path'])
print(path)

What this gives me is this

c:\directory\my_subdirectory\file.txt

Whereas I'm looking for it to output something like:

'c:\current_working_directory\output_location\directory\my_subdirectory\file.txt'

The issue is because the object['path'] is a variable I'm not sure how to escape it as a raw string. And so I think the escapes are breaking it. I can't guarantee there will always be a leading slash in the object['path'] value so I don't want to simply trim the first character.

I was hoping there was an elegant way to do this using pathlib that didn't involve ugly string manipulation.

Upvotes: 1

Views: 1011

Answers (2)

Carl_M
Carl_M

Reputation: 948

import pathlib

object = {'path': '/my_directory/my_subdirectory/file.txt'}
output = "output_location"
# object['path'][1:] removes the initial '/'
path = pathlib.PureWindowsPath(pathlib.Path.cwd()).joinpath(output,object[
    'path'][1:])
# path = pathlib.Path.cwd().joinpath(output,object['path'])
print(path)

Upvotes: 0

smcjones
smcjones

Reputation: 5610

Try lstrip('/')

You want to remove your leading slash whenever it’s there, because pathlib will ignore whatever comes before it.

Upvotes: 3

Related Questions