2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonのrelative_to()で相対パスを指定しようとしたらはまった

Posted at

概要

絶対パスから相対パスを取得するために以下のようなコードを実行した


import pathlib

p = pathlib.Path()
file_path = 'image-db'
file_path_rel = p.cwd().relative_to(file_path)

エラー


ValueError: '/directory/of/python' does not start with 'image-db'

relative_to()の中身がカレントディレクトリより外にあると動かないらしい.

対策

os.path.reipath('行先', '起点')を使えば複雑な相対パスも取得できる.

file_path_rel = os.path.relpath(file_path, os.getcwd())

参考サイト

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?