Pathlibで半角スペースを含むフォルダにアクセスできなかった話
Pythonのお勉強でPathlibを扱っていた時に詰まったので解決策を示しておきます。(Mac)
注意
-
@shiracamus さんより指摘
- Windows環境ではパスの区切り文字が違うのでこの解決策では正常に動作しません
-
re.sub(r'\\ ',' ',str(x))
とすることでWindowsに対応
問題内容
- 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
Author And Source
この問題について(Pathlibで半角スペースを含むフォルダにアクセスできなかった話), 我々は、より多くの情報をここで見つけました https://qiita.com/tohtoh103/items/5f21b3918095f5db58df著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .