I read Python pathlib
is supposed to make cross-platform code easier, but it's not recognizing backslash escaped spaces. I could work around this manually with str.replace()
, but what's the most Pythonic way to handle it? For example, I want the user to drag a file onto the terminal:
from pathlib import Path
instr = input('Drag a file here: ').strip()
infile = Path(instr)
print(infile.exists())
This code doesn't work if the input path has a space in it because macOS automatically adds the backslash escape when you drag a file onto the Terminal:
% python3 test.py
Drag a file here: /Users/Shared/folder\ one/file1
False
Someone suggested that this is duplicate of this question, but none of those answers are sufficient. I already acknowledged that this can be done manually, but I was hoping for a Pythonic method using pathlib
.
- The first answer is for Python 2, but can be modified for Python 3 based on ChristopheD's comment:
instr.encode('utf-8').decode('unicode_escape')
With my given example, this produces '/Users/Shared/folder\\ one/file1'
which fails the Path.exists()
test.
- The second answer raises a SyntaxError due to the forward slash.
ast.literal_eval(instr)
- The third and fourth answers are very similar to the first, and they produces the same result:
decode(encode(instr, 'latin-1', 'backslashreplace'), 'unicode-escape')