1

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.

  1. 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.

  1. The second answer raises a SyntaxError due to the forward slash.
ast.literal_eval(instr)
  1. 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')
Elliott B
  • 980
  • 9
  • 32
  • 1
    @CharlesDuffy thank for that tip. It works using `Path(shlex.split(instr)[0])`. You could write that as an answer, because none of the suggestions on the other question work here. – Elliott B Feb 03 '21 at 01:09
  • @ElliotB, since you've confirmed that that answers your question, I'll remove the other duplicate from the list, leaving only the one that already has answers describing the `shlex` module. – Charles Duffy Feb 03 '21 at 01:12

0 Answers0