首页 > 解决方案 > Python如何遍历文件目录让程序知道如何遍历到最后一个文件

问题描述

Python如何遍历文件目录,让程序知道要遍历到最后一个文件?我已经尽力了。这不好。一个目录下有几个文件夹,每个文件夹有几十个子文件夹,每个文件夹有两个文件。我只能非常严格地识别最后一个文件。

def openfile(inputdir):
global total,namebefor,nameafter,array
file = os.listdir(inputdir)
for fi in file:
    fidir = os.path.join(inputdir, fi)
    if os.path.isfile(fidir) and os.path.splitext(fidir)[1] in [".CSV"]:
        news = fidir.split("\\")
        nowname = news[-3]
        namebefor = nowname
        if namebefor == nowname:
            if namebefor !=nameafter:
                if nameafter != namebefor and array!=[]:
                    print(nameafter)
                    print(array)
                    print(int(total / 2))
                    array = []
                    total = 0
                else:
                    array.append(fidir)
                    total = total+1
            else:
                array.append(fidir)
                total = total + 1
                if nameafter == namebefor and array[-1].split("\\")[-1] == "9.CSV":
                    print(array)
                    print(nameafter)
                    print(int(total / 2))
                    array = []
                    total = 0
        nameafter = nowname
    elif os.path.isdir(fidir):
            openfile(fidir)

在此处输入图像描述

如果我不使用 "and array [-1].split("\") [-1]="9.CSV":" 在这种情况下,就无法打印出 YD-4 的路径。但是太死板了。如果我的最后一个不是 9.CSV,我必须不断更改条件。

标签: python

解决方案


enter code hereafor dirpath, dirnames, filenames in os.walk(".."):
for filepath in filenames:
    if os.path.splitext(os.path.join(dirpath, filepath))[1] in [".CSV"]:
        nowpath = os.path.join(dirpath, filepath)
        total += 1
        nowname =dirpath.split("\\")[-2]
        namebefor=nowname
        if namebefor==nowname:
            if nameafter!=namebefor:
                if namebefor!=nameafter and array!=[]:
                    print("%s" % array)
                    array = []
                    total = 0
                    array.append(nowpath)
                    total += 1
                else:
                    array.append(nowpath)
            else:
                array.append(nowpath)
            nameafter=nowname
        # print(os.path.splitext(os.path.join(dirpath, filepath))[0])
        # print(os.path.join(dirpath, filepath))

推荐阅读