0

1)以下语句工作正常

test_suite_name = [name for name in os.listdir(".") if (os.path.isdir(name))]

但我需要查看“./squish”中的目录。

test_suite_name = [name for name in os.listdir("./Squish") if (os.path.isdir(name))] 

但是这个语句不起作用......请告诉我如何更正它,我认为 if 语句需要一些更正。

2)还有我应该使用什么脚本格式来显示以“test_”开头的文件夹说,

我有很多文件夹,有些以“test_”为前缀,这些文件夹可以位于放置脚本的上方或下方的文件夹结构中。

“test_”文件夹可以是 /xyz/abc 文件夹下的任何位置,该文​​件夹可以是 python 脚本所在位置上方或下方的任何位置

4

3 回答 3

0

1)问题是,该名称只是子目录的名称,即test而不是./Squish/test

改为使用os.path.isdir(os.path.join('.', 'Squish', name))

如果您在 中查找文件夹.,则没有问题,因为 isdir 在给定相对路径的情况下查找当前目录。

2)您可以将列表理解扩展到

[name for name in (...) if os.path.isdir(...) and name.startswith('test_')]
于 2013-04-19T15:01:55.993 回答
0

你看,name迭代器中的变量只包含一个特定的文件或目录名,而不是整个路径。所以,

path = './Squish'
dirs = [name for d in os.listdir(path) 
        if os.path.isdir(os.path.join(path, name))]

应该做。

请注意,sorted(dirs)由于os.listdir().

于 2013-04-19T14:56:56.707 回答
0

对于第一个问题:

 test_suite_name = [name for name in os.listdir("./Squish") if os.path.isdir(os.path.join("./Squish", name))]

至于你的第二个问题,你可以做两件事:

1)使用完整路径;例如:r'C:\Windows\System32\calc.exe'

2)假设您的脚本位于C:\Documents and Settings\User\Desktop,并且您要指定log.txt位于C:\Documents and Settings文件夹中的文件。

您可以使用'..'来指定当前位置的父目录。因此,如果您在C:\Documents and Settings\User\Desktop,那么r'..\..\log.txt'将参考C:\Documents and Settings\log.txt

于 2013-04-19T14:58:32.030 回答