1
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 5 years have passed since last update.

pythonメモ 噛み砕いて覚えるos.pathの一部

Last updated at Posted at 2019-03-05

特定のファイルを他のディレクトリから参照したい場合に衝突した
pathの取得の分かった部分だけ (最初いがいprint()は割愛しています

main.py
import os

print(__file__)
# これで実行中の.pyの絶対パスが分かる

os.path.abspath('test.txt')
# 実行中の.pyと同じディレクトリならばこれでパスを調べれる

os.path.dirname(__file__)
# これで実行している.pyが存在するディレクトリのパスがわかる

os.path.dirname(os.path.dirname(__file__))
# どうやら上位のディレクトリにどんどんいけそうだ

dir_path = os.path.dirname(os.path.dirname(__file__))
new_path = os.path.join(dir_path, 'hello.txt')
# これでパスを繋げることができるのでディレクトリを探したりもできそうだ
結果.py
C:\User\mpec\python\main.py

C:\User\mpec\python\test.txt

C:\User\mpec\python

C:\User\mpec

C:\User\mpec\hello.txt

まとめ

pathlibの方が良いみたいだな。。。

また、お気づきの点がありましたら遠慮なくご指摘お願いいたします。

1
1
1

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