如何在python中扫描目录?

时间:2014-03-05 19:23:01

标签: python

我有一个python脚本试图将两个文件相互比较并输出差异。但是我不确定究竟发生了什么,因为当我运行脚本时它会给我一个错误

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\api\\API_TEST\\Apis.os\\*.*'

我不知道为什么要附加*。 *在文件扩展的末尾。

这是我目前的职能:

def CheckFilesLatest(self, previous_path, latest_path):

    for filename in os.listdir(latest_path):

        previous_filename = os.path.join(previous_path, filename)
        latest_filename = os.path.join(latest_path, filename)

        if self.IsValidOspace(latest_filename):

            for os_filename in os.listdir(latest_filename):
                name, ext = os.path.splitext(os_filename)

                if ext == ".os":
                    previous_os_filename = os.path.join(previous_filename, os_filename)
                    latest_os_filename = os.path.join(latest_filename, os_filename)

                    if os.path.isfile(latest_os_filename) == True:

                        # If the file exists in both directories, check if the files are different; otherwise mark the contents of the latest file as added.
                        if os.path.isfile(previous_os_filename) == True:
                            self.GetFeaturesModified(previous_os_filename, latest_os_filename)
                        else:
                            self.GetFeaturesAdded(latest_os_filename)

        else:
            if os.path.isdir(latest_filename):
                self.CheckFilesLatest(previous_filename, latest_filename)

有关为什么它无法扫描目录并查找os文件的任何想法?

它失败了:

for os_filename in os.listdir(latest_filename):

首先从

调用代码
def main():
    for i in range(6, arg_length, 2):
        component = sys.argv[i]
        package = sys.argv[i+1]

        previous_source_dir = os.path.join(previous_path, component, package)
        latest_source_dir = os.path.join(latest_path, component, package)

        x.CheckFilesLatest(previous_source_dir, latest_source_dir)
        x.CheckFilesPrevious(previous_source_dir, latest_source_dir)

谢谢

2 个答案:

答案 0 :(得分:1)

os.listdir()要求latest_path参数是您所声明的目录。但是,latest_path作为参数传入。因此,您需要查看实际创建latest_path的代码,以确定放入''的原因。由于您以递归方式调用它,因此请先检查原始调用(第一次) )。看来调用CheckFilesLatest()的基本代码正在尝试设置搜索命令以查找目录“C:\ api \ API_TEST \ Apis.os”中的所有文件。您需要首先拆分文件指示符,然后做检查。

答案 1 :(得分:0)

如果要以递归方式浏览目录,使用os.walk将比使用递归函数调用的复杂处理更好,更简单。请查看文档:{​​{3}}