关于Python中os.walk(path)循环的问题

使用Python对文件夹中的 .sig 后缀文件进行操作,操作后转存到路径下的xls文件夹下,如果文件夹中没有.sig 后缀文件, 会输出 “所给路径不存在.sig文件” ,但是每执行一次就会多输出一次,关终端、重启软件都无法制止它的增长。不懂其中奥妙,求解。。

img

path = "E:\\数据\\scr2 - 副本"
have_sig = 0
isExists = os.path.exists(path)
if not isExists:
    print("提供的存储.sig文件路径不存在")
else:
    for curDir, dirs, files in os.walk(path):
        isExists = os.path.exists(curDir+"\\xls")
        if not isExists :
            os.makedirs(curDir+"\\xls")
        for file in files:
            if file.endswith(".sig"):
                have_sig = have_sig+1
                # print(curDir+"\\"+file)
                # print(curDir+"\\"+file[:-3])
                os.rename(curDir+"\\"+file,curDir+"\\"+file[:-3]+"txt")
                pass
                fo = open(curDir+"\\"+file[:-3]+"txt", "r")
                date = fo.read()
                date = date.split("\n")
                datas = np.array(date[30:]) 
                code = np.empty(0)
                for i in datas:
                    i = i.split()
                    for j in i:
                        code = np.append(code,float(j))
                code = code.reshape(-1,4)
                # print(code.shape())#1023,4
                fo.close()

                workbook = xlwt.Workbook(encoding = 'ascii')
                worksheet = workbook.add_sheet('sheet')
                worksheet = workbook.get_sheet('sheet')
                for row in range(0,len(code),1):
                    for column in range(0,4,1):
                        worksheet.write(row, column, code[row][column])
                workbook.save(curDir+"\\xls\\"+file[:-3]+"xls")
        if have_sig == 0:
            print("所给路径不存在.sig文件")
        else:
            print("处理文件数量:",have_sig)
 

运行结果及报错内容

(18次)
E:\9-python\opencv>python -u "c:\Users\star\Desktop\Untitled-1.py"
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
(19次)
E:\9-python\opencv>python -u "c:\Users\star\Desktop\Untitled-1.py"
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件
所给路径不存在.sig文件

我的解答思路和尝试过的方法

尝试输出print(os.walk(path))
但是结果都一样:
<generator object _walk at 0x0000022483B67350>

我想要达到的结果

应该是自己的知识盲区,望指导

isExists = os.path.exists(curDir+"\\xls")
if not isExists :
            os.makedirs(curDir+"\\xls")

这段代码(上述代码在第9、10行)是你每次都会多一次的原因所在,由于是遍历所有子目录,所以肯定不是每个文件夹都有xls这个子目录的,这样就导致了你每次都会新建一个xls文件夹,导致每次多输出一次。

如果只是获取一个文件夹下所有文件,可以用os.listdir()