【问题标题】:A pythonic way of finding folder一种查找文件夹的pythonic方法
【发布时间】:2016-12-14 19:03:11
【问题描述】:

从提供的路径中查找子文件夹的最 Pythonic 方式是什么?

import os

def get_folder(f, h):
  pathList = f.split(os.sep)
  sourceList = h.split(os.sep)

  src = set(sourceList)
  folderList = [x for x in pathList if x not in src]

  return folderList[0]


print get_folder("C:\\temp\\folder1\\folder2\\file.txt", "C:\\temp") # "folder1" correct
print get_folder("C:\\temp\\folder1\\file.txt", "C:\\temp") # "folder1" correct
print get_folder("C:\\temp\\file.txt", "C:\\temp") # "file.txt" fail should be "temp"

在上面的示例中,我在“文件夹 2”中有一个 file.txt。提供路径“C:\temp”作为查看起点。

我想从中返回子文件夹;如果有问题的文件在源文件夹中,它应该返回源文件夹。

【问题讨论】:

  • 您应该使用os.path.walk 之类的东西在路径的每个分支中迭代地遍历所有文件,并查看这个答案stackoverflow.com/questions/2860153/… 了解如何在您找到的条件下获取父文件夹文件,否则继续往上。
  • 也使用os.path.join而不是手动向函数发送字符串

标签: windows python-2.7 path directory


【解决方案1】:

试试这个。我不知道你为什么说folder1 对第一个例子是正确的,不是folder2 吗?我也在 Mac 上,所以 os.sep 不适合我,但你可以调整它。

import os

def get_folder(f, h):
    pathList = f.split("\\")

    previous = None

    for index, obj in enumerate(pathList):
        if obj == h:
            if index > 0:
                previous = pathList[index - 1]

    return previous


print get_folder("C:\\temp\\folder1\\folder2\\file.txt", "file.txt") # "folder2" correct
print get_folder("C:\\temp\\folder1\\file.txt", "file.txt") # "folder1" correct
print get_folder("C:\\temp\\file.txt", "file.txt") # "file.txt" fail should be "temp"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多