【问题标题】:How to get sibling folder path in python?如何在python中获取兄弟文件夹路径?
【发布时间】:2018-03-06 07:04:31
【问题描述】:

xyzd:/ 中的文件夹

d:/x(当前)

d:/y

d:/z

从给定的x 文件夹路径中获取yz 文件夹路径的最佳方法是什么。

【问题讨论】:

    标签: python python-3.x path pathlib


    【解决方案1】:

    使用 pathlib 模块

    In [39]: from pathlib import Path
    
    In [40]: def get_siblings(path):
        ...:     parent = path.parent
        ...:     for x in parent.iterdir():
        ...:         if x.is_dir() and x != path:
        ...:             yield x
        ...:             
    
    In [41]: for f in get_siblings(Path.cwd()):
        ...:     print(f)
        ...:     
    /mnt
    /snap
    /lib
    /bin
    /tmp
    /sbin
    /usr
    /lib64
    /opt
    /lib32
    /boot
    /etc
    /media
    

    【讨论】:

    • 简短的回答是,获取父级并迭代。
    【解决方案2】:

    我认为这几乎可以满足您的需求。

    import os
    from os.path import join, getsize
    for root, dirs, files in os.walk('C:/your_path_here/'):
        print(root, "consumes", end=" ")
        print(sum(getsize(join(root, name)) for name in files), end=" ")
        print("bytes in", len(files), "non-directory files")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2014-02-25
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多