Pathlibで半角スペースを含むフォルダにアクセスできなかった話


Pythonのお勉強でPathlibを扱っていた時に詰まったので解決策を示しておきます。(Mac)

注意

  • @shiracamus さんより指摘
    • Windows環境ではパスの区切り文字が違うのでこの解決策では正常に動作しません
      • re.sub(r'\\ ',' ',str(x))とすることでWindowsに対応

問題内容

例) 以下のコードで ~/test blank folder/ の存在を確認する

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

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

バックスラッシュで半角スペースがエスケープされているので、上手く動作しない
シングルクォーテーションやダブルクォーテーションで囲んでみたが意味無し

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

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

解決策

エスケープのバックスラッシュを消す。解決
※2020/12/23 12:22 変更

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