【问题标题】:Getting paths to all files in a directory (but not absolute path) in Python 3在 Python 3 中获取目录中所有文件的路径(但不是绝对路径)
【发布时间】:2020-07-15 05:46:49
【问题描述】:

我有一个目录DATA,其中包含几个子目录,在每个子目录中,还有更多的目录和文件。

这是我的代码:

for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
   for f in filenames:
       print(os.path.abspath(os.path.join(dirpath, f)))

这段代码打印出来的结果是绝对目录(例如“/Users/.../Data/SubFile/SubFile.txt”)

我想要的结果是(例如“Data/SubFile/Subfile.txt”)

【问题讨论】:

    标签: python python-3.x file operating-system


    【解决方案1】:

    像这样简单的事情怎么样:

    dir_path = "/Users/.../DATA"
    
    for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
       for f in filenames:
           print(os.path.abspath(os.path.join(dirpath, f))[len(dir_path):])
    

    【讨论】:

      【解决方案2】:

      使用os.path.commonprefix():

      common_prefix = os.path.commonprefix(["/Users/.../DATA"])
      for dirpath, subs, filenames in os.walk("/Users/.../DATA"):
          for f in filenames:
              print(os.path.relpath(os.path.join(dirpath, f), common_prefix))
      
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2012-04-06
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 2018-12-27
        • 1970-01-01
        • 2012-10-04
        • 2014-01-26
        相关资源
        最近更新 更多