Python如何遍历文件目录,以使程序知道如何遍历最后一个文件

时间:2019-03-22 12:26:17

标签: 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)

enter image description here

如果我不使用“和数组[-1]。split(“ \”)[-1] =“ 9.CSV”:“ 在这种情况下,您将无法打印出YD-4的路径。但这太死板了。如果我的上一个不是9.CSV,则必须不断更改条件。

1 个答案:

答案 0 :(得分:0)

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))