c# - 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# 代码中得到了有效的结果,也许应该很高兴,但我想了解为什么两个结果之间存在差异。
解决方案
没有足够的声誉来发表评论,但是在使用 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)
推荐阅读
- javascript - 光滑的垂直滑块问题
- c++ - 如何减少应用程序的 CPU 使用率?
- sql-server - 如何使用 SSIS 从 ActiveMQ 队列中读取数据?
- ionic-framework - Uncaught (in promise):导航堆栈至少需要一个根页面
- sap - SAP HANA | 截断分区
- c++ - 是否将参数加载到空函数的缓存中?
- cobol - + COBOL 中第 7 列中的符号
- javascript - 我可以在反应中使用 fetch 发布文本数据吗
- r - 可过滤的列标题在 R 中的 DT 中未对齐
- javascript - 刷新用循环填充的 DataTables 表