xor*_*aul 2 python directory path
我已经有了这段功能正常的代码,但在写完之后,我确实感到尖叫的冲动"它还活着,它还活着!".
我想要做的是获取文件夹"modules"作为其父文件夹,例如从/ home/user/puppet/modules/impuls-test/templates/apache22 /我想/ home/user/puppet/modules/IMPULS测试/
我想出的是以下内容:
user@server:~/puppet/modules/impuls-test/templates/apache22$ python
Python 2.4.2 (#1, Apr 13 2007, 15:38:32)
[GCC 4.1.0 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> cwd = os.getcwd()
>>> path = cwd
>>> print "cwd: %s" % cwd
cwd: /home/user/puppet/modules/impuls-test/templates/apache22
>>> for i in xrange(len(cwd.split('/'))):
... (head, tail) = os.path.split(path)
... print "head: %s" % head
... print "tail: %s" % tail
... if tail == 'modules':
... moduleDir = head + '/modules/' + cwd.split('/')[i+2] + '/'
... print "moduleDir: %s" % moduleDir
... break
... else:
... path = head
...
head: /home/user/puppet/modules/impuls-test/templates
tail: apache22
head: /home/user/puppet/modules/impuls-test
tail: templates
head: /home/user/puppet/modules
tail: impuls-test
head: /home/user/puppet
tail: modules
moduleDir: /home/user/puppet/modules/impuls-test/
Run Code Online (Sandbox Code Playgroud)
我得到当前的工作目录并使用了os.path.split很长时间,直到它到达modules文件夹.使用普通string.split函数迭代cwd,我可以将moduleDir原始cwd.split('/')数组附加到当前头部.
有人能告诉我一个更好/ pythonic方式来做到这一点?当然我可以检查当前的头是否以模块结束然后追加当前的尾部,但这只会使循环中断更快并且仍然是丑陋的.
path = "/home/user/puppet/modules/impuls-test/templates"
components = path.split(os.sep)
print str.join(os.sep, components[:components.index("modules")+2])
Run Code Online (Sandbox Code Playgroud)
版画
/home/user/puppet/modules/impuls-test
Run Code Online (Sandbox Code Playgroud)
由于 os.path.normpath 处理“..”运算符,因此您可以只添加“..”并让normpath 完成工作:
>>> path = "/home/user/puppet/modules/impuls-test/templates"
>>> os.path.normpath(os.path.join(path, ".."))
'/home/user/puppet/modules/impuls-test'
Run Code Online (Sandbox Code Playgroud)