【问题标题】:Get customize Path of File found with os.walk获取使用 os.walk 找到的自定义文件路径
【发布时间】:2019-12-15 18:39:50
【问题描述】:

我正在尝试公开使用 os.walk 找到的文件的选择性路径。 walk 函数工作正常,并且正在公开我想要的所有文件,但是现在我只能公开文件名或文件的完整路径。

path = 'C:/Users/testing_recurssion' for root, d_names, f_names in os.walk(path): for name in f_names: print(os.path.join(root, name))

返回
C:/Users/testing_recurssion\folder1\file3.txt
C:/Users/testing_recurssion\folder1\folder3\file4.txt

但是,我希望它返回
folder1\file3.txt
folder1\folder3\file4.txt**

【问题讨论】:

    标签: python path operating-system os.walk


    【解决方案1】:

    使用os.relpath

    directory = "C:/Users/testing_recurssion"
    for root, d_names, f_names in os.walk(directory):
        for name in f_names:
            path = os.path.join(root, name)
            print(os.path.relpath(path, directory))
    
    

    另外 - 考虑使用更新且面向对象的pathlib.Path

    from pathlib import Path
    
    directory = Path("C:/Users/testing_recurssion")
    for path in directory.rglob("*"):
        print(path.relative_to(directory))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2017-10-18
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多