python根据平台以不同顺序列出目录

问题描述

| 我正在使用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)在d:\\ ssptemp下的所有目录上进行os.walk 2)查找文件名中带有\'IWPCPatch \'的所有文件 3)检查\'IWPCPatchFinal_a.wsf \'文件内容 4)如果内容为true,则将该文件的路径添加到列表中。 我的问题是,在我的XP机器上,它工作正常。如果我打印出列表的结果,则会得到我上面列出的顺序的几项。 当我将其移至Server 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
    

解决方法

os.walk
中的目录顺序不一定是字母顺序(我认为这实际上取决于它们在文件系统上的存储方式)。如果您不更改目录内容(例如,重复调用将返回相同的顺序),则在相同的精确目录(相同的文件系统)上可能会很稳定,但是该顺序不一定是字母顺序的。 如果要有文件名的有序列表,则必须先构建该列表,然后再对其进行排序。     ,
for path,dirs,files in os.walk(\'d:\\ssptemp\'):

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

    print \"parsing dir(s)\"
    # ...