1
path = "C:/Users/bg/Documents/Brad/Code/Visual Studio/"

def getUnitTest(path):
    foundFiles = []

    for r,d,f in os.walk(path):
        for files in f:
            if files.endswith('.UnitTests.vbproj'):
                path2 = os.path.split(files)
                print path2
                foundFiles.append(path2)
    return foundFiles

foundFiles[] (遍历后)=

[('', 'bg.APDS.UnitTests.vbproj')
('', 'bg.DatabaseAPI.UnitTests.vbproj')
('', 'bg.DataManagement.UnitTests.vbproj')
('', 'bg.FormControls.UnitTests.vbproj')]
('', 'Cooper.Geometry.UnitTests.vbproj')

我有这个功能,到目前为止效果很好。但是,foundFiles 中每个字符串的前 4 个空格具有我需要摆脱的“''”格式。最好使用 string.strip 或 string.replace 或任何其他方式吗?提前致谢!

编辑1:

def getUnitTest(path):
foundFiles = []

for r,d,f in os.walk(path):
    for files in f:
        if files.endswith('.UnitTests.vbproj'):
            path2 = os.path.split(files)
            print path2
            foundFiles.append(path2)
foundFiles2= [ str(value for value in file if value) for file in foundFiles]
return foundFiles2

这就是我到目前为止所拥有的,它仍然没有摆脱第一个元组,我应该将值更改为它实际代表的值吗?抱歉,如果这是一个愚蠢的问题,我仍然是新手程序员。

4

2 回答 2

0

*.UnitTests.vbproj在您的目录中查找的一种更简单的方法path是使用glob

import os, glob

def getUnitTest(path):
    return glob.glob(os.path.join(path, "*.UnitTests.vbproj"))

并每行打印一个结果:

print "\n".join(getUnitTest(path));
于 2013-05-16T15:36:49.813 回答
0

替换元组中的空格

您不是要删除字符串的一部分,而是要从元组中删除空字符串(您在 中有一个元组列表,您可以这样做:foundFiles

注意:由于元组是不可变的,一旦定义我们就不能编辑它们

foundFilesFixed = [str(value for value in file if value) for file in foundFiles]

这将复制所有元组值,foundFiles只要foundFilesFixed它们不为假(空空格,null 等)。

这将取代这个:

[
    ('', 'bg.APDS.UnitTests.vbproj')
    ('', 'bg.DatabaseAPI.UnitTests.vbproj')
    ('', 'bg.DataManagement.UnitTests.vbproj')
    ('', 'bg.FormControls.UnitTests.vbproj')
]

有了这个:

[
    'bg.APDS.UnitTests.vbproj'
    'bg.DatabaseAPI.UnitTests.vbproj'
    'bg.DataManagement.UnitTests.vbproj'
    'bg.FormControls.UnitTests.vbproj'
]

我在这里假设所有元组都有两个值,一个为空,一个为文件名。如果它们有可能包含多个值,则需要将str(我的函数更改为tuple(.

替代方案:特定于应用程序

正如乔丹在评论中指出的那样,对于您的示例,您可以这样做:

return [str(value[1]) for value in foundFiles]

但是return foundFiles,这不太可能对未来的读者起作用,因此不想将注意力集中在它上面。

于 2013-05-16T15:37:16.403 回答