128:ファイル名を構成要素に分解する
ファイル名を構成要素に分解するには、os.pathモジュールを用いる。ファイル名やbasename()関数で、パス名とファイル名はsplit()を使うと、タプルとして取り出すことが出来る。
>>> import os.path
>>> file='C:/Documents and Settings/Administrator/My Documents/input.txt'
>>> os.path.basename(file)
'input.txt'
>>> os.path.split(file)
('C:/Documents and Settings/Administrator/My Documents', 'input.txt')
OSによって、パスの区切りも文字が違うので、linuxとWinodowの両方で動かすプログラムを書くときは、os.path.normpath()を使って利用するOSに対応したパスにしておいたほうがよい。
>>> os.path.normpath(file) 'C:\\Documents and Settings\\Administrator\\My Documents\\input.txt'