Tim*_*der 7 python build filepath dirname os.path
我发现自己需要在源树中获取python文件的父目录,该源目录树是多个目录,具有一定的规律性.不得不多次打电话给dirname是笨重的.
我环顾四周,很惊讶没有发现这个帖子.
一般情况是:
import os.path as op
third_degree_parent = op.dirname(op.dirname(op.dirname(op.realpath(__file__))))
Run Code Online (Sandbox Code Playgroud)
是否有更惯用的方法来执行此操作,不需要嵌套的dirname调用?
Mar*_*ers 12
规范化相对路径; os.pardir是父目录,根据需要重复多次.它也可以通过os.path.pardir:
import os.path as op
op.abspath(op.join(__file__, op.pardir, op.pardir, op.pardir))
Run Code Online (Sandbox Code Playgroud)
由于尚未演示,这里是使用递归函数的答案。
功能
import os
def parent(path, level = 0):
parent_path = os.path.dirname(path)
if level == 0:
return parent_path
return parent(parent_path, level - 1)
Run Code Online (Sandbox Code Playgroud)
说明
例子
>>> parent('/my/long/path/name/with/a/file.txt')
'/my/long/path/name/with/a'
>>> parent('/my/long/path/name/with/a/file.txt', 0)
'/my/long/path/name/with/a'
>>> parent('/my/long/path/name/with/a/file.txt', 4)
'/my/long'
Run Code Online (Sandbox Code Playgroud)
4 年后,有人在 2018 年添加了答案,为什么不添加我的答案呢?其他答案要么很长,要么如果需要更多的父母,就会变得很长。假设您需要 7 位父母。这就是我所做的
os.path.abspath(__file__ + 8 * '/..')
Run Code Online (Sandbox Code Playgroud)
请注意额外的 (8=7+1) 以删除 7 个父级以及文件名。不需要普遍os.path.pardir理解并且会做正确abspath的/..事情。还有一个优点是父母的数量可以是动态的,在运行时确定。
相比之下,使用已接受答案的等效内容(更长且不太明显):
import os.path as op
op.abspath(op.join(__file__, op.pardir, op.pardir, op.pardir, op.pardir, op.pardir, op.pardir, op.pardir))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1448 次 |
| 最近记录: |