2013-07-06 16 views
5

私はディレクトリbar内のディレクトリfooとファイルbar_file.txt内のファイルfoo_file.txtで、ディレクトリfoo内のディレクトリbarを持っています。すなわちパイソンos.path.relpath機能を使用してPythonのos.path.relpath行動

computer$ ls 
foo/ 
computer$ ls foo/ 
bar/ foo_file.txt 
computer$ ls foo/bar/ 
bar_file.txt 

、私は期待して:

os.path.relpath('foo/bar/bar_file.txt', 'foo/foo_file.txt') 

は私を与えるために:

'../bar/bar_file.txt' 

理由:

'bar/bar_file.txt' 

しかし、それは実際に私を与えますこれは?私が望む行動を得るための簡単な方法はありますか?

EDIT:これは、Python 2.7.3とLinux上で

+1

は私が 'os.path.relpath( 'FOO /バー/ bar_file.txt'、os.path.dirname( 'FOO/foo_file.txtを'))'使用することができ実現されています私が望む結果を得るために。元のコードが機能しない理由はまだ不思議です。 – jveldridge

答えて

5

os.path.relpath()その引数がディレクトリであることを前提としています。

>>> os.path.join(os.path.relpath(os.path.dirname('foo/bar/bar_file.txt'), 
     os.path.dirname('foo/foo_file.txt')), 
     os.path.basename('foo/bar/bar_file.txt')) 
'bar/bar_file.txt' 
+0

ありがとうございます。これは正しい動作のようには見えないので、私はバグを提出しました:[http://bugs.python.org/issue18389](http://bugs.python.org/issue18389) – jveldridge

3
os.path.relpath(arg1, arg2) 

ARG1のディレクトリからARG2の相対パスを与えます。あなたのケースでarg2からarg1に到達するには、1つのディレクトリ(..)をcdして、barディレクトリ(bar)に行き、次にbar_file.txtに移動する必要があります。したがって、相対パスは

../bar/bar_file.txt 
+0

これは正解です。 – jkdev

+1

'os.path.relpath(arg1、arg2)'は** arg2 **のディレクトリの中から** arg1 **の相対パスを与えます – 4Oh4