开发者

How can you use os.chdir to go to a path minus the last step of it?

For example, a method is passed a path as a parameter, this path might be "C:/a/b/c/d", what if I want to use os.chdir() to change to C:/a/b/c (without the last folder)? Can 开发者_如何转开发os.chdir() take the ".." command?


os.chdir() can take '..' as argument, yes. However, Python provides a platform-agnostic way: by using os.pardir:

os.chdir(os.pardir)


You could use os.path.dirname:

In [1]: import os.path

In [2]: os.path.dirname('C:/a/b/c/d')
Out[2]: 'C:/a/b/c'

edit: It's been pointed out that this doesn't remove the last component if the path ends with a slash. As a more robust alternative, I propose the following:

In [5]: os.path.normpath(os.path.join('C:/a/b/c/d', '..'))
Out[5]: 'C:/a/b/c'

In [6]: os.path.normpath(os.path.join('C:/a/b/c/d/', '..'))
Out[6]: 'C:/a/b/c'

The '..' can be replaced with os.path.pardir to make the code even more portable (at least theoretically).


The os.path module has some functions that are useful for this sort of thing.

os.path.normpath() can be used to convert a path containing references like .. to an absolute path. This would ensure consistent behaviour regardless of how the operating system handles paths.

os.chdir(os.path.normpath("C:/a/b/c/..")) should accomplish what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜