首页 > 解决方案 > Python os.walk 返回的文件少于 C# Directory.GetFiles

问题描述

为什么 python 的 os.walk 返回的文件比使用 C# Directory.GetFiles 少?使用相同的起始目录时,我希望得到相同的结果。

我的 Python 代码是:

import os
#Note that startdir is entered as 'Z:\directoryname', same as c# below
startdir = input("Enter Starting Path: ")
fileList = []
for(dirname, dirs, files) in os.walk(startdir, followlinks=True):
    for filename in files:
        thefile = os.path.join(dirname,filename)
        fileList.append(thefile)
printline = 'Total: ' + str(len(fileList))
print(printline)

C# 很简单:

using System.IO;
...
string rootPath = @"Z:\directoryname";
string[] dirReturn = Directory.GetFiles(rootPath, "*", SearchOption.AllDirectories);

但是,Python 在数组中返回 653231 个文件,而 C# 返回 653271(相差 40)。

我检查了 C# 数组是否有重复项,但没有发现。我比较了这两个数组,发现 Python 数组中缺少 C# 数组中的文件;C# 文件都是有效的。

我承认我似乎从我的 C# 代码中得到了有效的结果,也许应该很高兴,但我想了解为什么两个结果之间存在差异。

标签: c#pythonmethods

解决方案


没有足够的声誉来发表评论,但是在使用 os.walk 时文件可能存在问题,这会阻止该方法实际读取文件。从文档

“默认情况下,scandir() 调用中的错误被忽略。如果指定了可选参数 onerror,它应该是一个函数;它将使用一个参数调用,即一个 OSError 实例。它可以报告错误以继续遍历,或引发异常以中止步行。请注意,文件名可用作异常对象的文件名属性。

尝试使用这样的东西:

import os

def error_os_walk(exception):
    print("Error in file, python can't read")

startdir = input("Enter Starting Path: ")
fileList = []
for(dirname, dirs, files) in os.walk(startdir, followlinks=True, onerror=error_os_walk):
    for filename in files:
        thefile = os.path.join(dirname,filename)
        fileList.append(thefile)
printline = 'Total: ' + str(len(fileList))
print(printline)

推荐阅读