The story that Pathlib could not access the folder containing the half-width space

I got stuck when I was working on Pathlib while studying Python, so I will show you the solution. (Mac)

Note

--Pointed out by @shiracamus --This solution does not work because the path delimiter is different in Windows environment --Supports Windows by setting re.sub (r'\\','', str (x))

the issue's details

Example) Check the existence of ~/test blank folder/with the following code

test.py


import pathlib
x = input('')
fpath = pathlib.Path(x)
print(fpath.exists())

python blankCharPathlib.py
path >>> ~/test\ blank\ folder 
~/test\ blank\ folder  False

It doesn't work because the backslash escapes the half-width space. I tried enclosing it in single quotes or double quotes, but it doesn't make sense

python blankCharPathlib.py
path >>> '~/test\ blank\ folder'
'~/test\ blank\ folder' False

python blankCharPathlib.py
path >>> "~/test\ blank\ folder"
"~/test\ blank\ folder" False

solution

Remove the escape backslash. Solution

test2.py


import pathlib
import re
x = input('path >>> ')
fpath = pathlib.Path(re.sub(r'\\ ',' ',str(x)))
print(str(fpath) ,fpath.exists())
python blankCharPathlib.py
path >>> ~/test\ blank\ folder  
~/test blank folder True

Recommended Posts

The story that Pathlib could not access the folder containing the half-width space
The story that 5GHz band access point could not be created on Ubuntu
The story that yapf did not work in vscode
The story that `while queue` did not work in python
The story that the version of python 3.7.7 was not adapted to Heroku
The story of the release work of the application that Google does not tell
The story that 2D list replacement did not work in python
[Web server] A story when I investigated because I could not access nginx