10

我正在使用 python 2.7 在 XPsp3 上编写和测试代码。我在带有 python 2.7 的 2003 服务器上运行代码。我的目录结构看起来像这样

d:\ssptemp
d:\ssptemp\ssp9-1
d:\ssptemp\ssp9-2
d:\ssptemp\ssp9-3
d:\ssptemp\ssp9-4
d:\ssptemp\ssp10-1    
d:\ssptemp\ssp10-2
d:\ssptemp\ssp10-3
d:\ssptemp\ssp10-4

在每个目录中都有一个或多个文件,文件名中包含“IWPCPatch”。

在这些文件之一(每个目录中一个)内,将有“IWPCPatchFinal_a.wsf”行

我所做的是

1) os.walk 遍历 d:\ssptemp 下的所有目录

2) 查找文件名中带有“IWPCPatch”的所有文件

3) 检查“IWPCPatchFinal_a.wsf”文件的内容

4)如果内容为真,我将该文件的路径添加到列表中。

我的问题是在我的 XP 机器上它工作正常。如果我打印出列表的结果,我会按照上面列出的顺序得到几个项目。

当我将它移动到服务器 2003 机器时,我以不同的顺序获得相同的内容。它是 ssp10-X,然后是 ssp9-X。这导致我在程序中的不同区域出现问题。

我可以从我的输出中看到它以错误的顺序开始 os.walk,但我不知道为什么会这样。

import os
import fileinput

print "--createChain--"

listOfFiles = []
for path, dirs, files in os.walk('d:\ssptemp'):

    print "parsing dir(s)"
    for file in files:
        newFile = os.path.join(path,file)
        if newFile.find('IWPCPatch') >= 0:
            for line in fileinput.FileInput(newFile):
                if "IWPCPatchFinal_a.wsf" in line:
                    listOfFiles.append(newFile)                            
                    print "Added", newFile

for item in listOfFiles:
    print "list item", item
4

2 回答 2

14
for path, dirs, files in os.walk('d:\ssptemp'):

    # sort dirs and files
    dirs.sort()
    files.sort()

    print "parsing dir(s)"
    # ...
于 2012-07-16T09:16:13.093 回答
13

目录的顺序os.walk不一定是字母顺序(我认为这实际上取决于它们如何存储在文件系统的目录中)。如果您不更改目录内容(即重复调用将返回相同的顺序),它可能在同一个确切的目录(在同一个文件系统上)上是稳定的,但顺序不一定是字母顺序。

如果您想要一个有序的文件名列表,您将必须构建该列表,然后自己对其进行排序。

于 2011-04-14T18:05:14.513 回答