1
2

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

1
Last updated at Posted at 2015-10-13

os.path.[functions]

ファイルパスとディレクトリパスの両方を処理できるスクリプト書こうとして思ったのと違う動きしたのでメモ。

最近よくつかったos.path.functionsについて。全部じゃありません、使ったやつだけ。
help(function)とか読んだわけではないので違う環境で再現性なくても怒らないでね!
もし便利なのがあったら教えて下さい

環境:

  • MacBook (12 inchのやつ) OS X 10.10
  • Python 2.7.10, ipython 4.0.0
  • 他なんか必要な情報あったっけ、、、

os.path.abspath(str)

作業ディレクトリ+ strを返す

単なる絶対パスへの変換ではありません。
また、ディレクトリ名を引数として渡した場合、最後のバックスラッシュがなくなります。

    print os.path.abspath('~/Documents/files/')
    # => <WorkingDir>/~/Documents/files
    # 最後の"/"が消えている

~ や $name みたいな環境変数は使えませんが、../../みたいな相対パスはちゃんと働きます。
環境変数たちはexpandusersとexpandvarsが必要です (下の方に説明)。

os.path.dirname(str)

strの文字列のうち、ディレクトリまでを返す。最後の/は消える。
多分次みたいな処理をしてるんだと思う。

dirname
    def dirname(filepath):
        dirs = filepath.split('/')
        return '/'.join(dirs[:-1])

splitとjoinはggrか、下を見て察して

    a = '/color/test/test/'
    print a.split('/')
# => ['', 'color', 'test', 'test', '']
    print '/'.join(a.split('/'))
# => '/color/test/test/'
    print '/'.join(a.split('/')[:-1])
# => '/color/test/test'

os.path.basename(str)

ファイル名を返す。str がディレクトリパス(/で終わってる)だったら空文字が帰ってくる。
多分処理内容は下の様な感じ。

    def basename(filepath):
        dirs = filepath.split('/')
        return dirs[-1]

os.path.expanduser(str)

ホーム記号(~)をログインユーザーで定義されているパスへ展開する。
たぶんデフォルトだと/Users/<username>/とか/home/<username>/とか1。

os.path.expandvars(str)

$マークで呼び出すような環境変数を展開します。$HOMEでも${HOME}でもいいみたい。
でもexpandvars($PATH)とかで呼び出しても":"が入ってるので結局split(':')とかやらないといけない。
しかもpathじゃない環境変数でも呼び出せる。
でも~は展開しない。なぜ別けたし。


事故例

事故例
    from os.path import dirname, abspath, expandusers, expandvars

    def smartpath(filepath):
        _dir = dirname(abspath(expandusers(expandvars(filepath))))
        _file = basename(abspath(expandusers(expandvars(filepath))))
        return [_dir,_file]

    print smartpath('$HOME/file')
    # => ['/Users/username','file']
    print smartpath('~/Documents/note/')
    #    ['/Users/username/Documents/note',''    ]    :想定
    # => ['/Users/username/Documents'     ,'note']    :実際    

こんな感じで、ファイルパスでもディレクトリパスでもおんなじようにしてディレクトリ名とファイル名が欲しかったのだけど、適当に関数を重ねたところ、ファイルパスは絶対でも相対でも大丈夫だったけど、ディレクトリパスだと最後のディレクトリ名がファイル名と誤認されちゃったということ。

結局はファイルパスかディレクトリパスかを判定してif分岐にしました。


  1. MacとLinuxでここのパスが違うのがなんでなんでしょう。Windowsは使ってないから知らない。 ↩

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?