Python如何遍历文件目录,让程序知道如何遍历到最后一个fi

2024-05-12 13:22:57 发布

您现在位置: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]。拆分(“\”[-1]=“9.CSV”: 在这种情况下,您无法打印YD-4的路径。但是它太僵硬了。如果我的最后一个不是9.CSV,我必须不断改变条件


Tags: and文件csvpath文件夹ifosarray
1条回答
网友
1楼 · 发布于 2024-05-12 13:22:57
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))

相关问题 更多 >