简体   繁体   English

具有for循环python的递归函数

[英]Recursive function with for loop python

I have a question that should not be too hard but it has been bugging me for a long time. 我有一个不应该太难的问题,但很长一段时间以来一直困扰着我。
I am trying to write a function that searches in a directory that has different folders for all files that have the extension jpg and which size is bigger than 0. 我正在尝试编写一个函数,该函数在具有不同文件夹的目录中搜索所有扩展名为jpg且大小大于0的文件。
It then should print the sum of the size of the files that are in these categories. 然后,应打印这些类别中文件的大小总和。

What I am doing right now is 我现在正在做的是

def myFuntion(myPath, fileSize): 

    for myfile in glob.glob(myPath): 
        if os.path.isdir(myFile):
            myFunction(myFile, fileSize)

        if (fnmatch.fnmatch(myFile, '*.jpg')):
            if (os.path.getsize(myFile) >  1):
                fileSize = fileSize + os.path.getsize(myFile)


    print "totalSize: " + str(fileSize)

This is not giving me the right result. 这没有给我正确的结果。 It sums the sizes of the files of one directory but it does not keep summing the rest. 它对一个目录的文件大小进行求和,但对其余目录不做求和。 For example if I have these paths 例如,如果我有这些路径

C:/trial/trial1/trial11/pic.jpg  

C:/trial/trial1/trial11/pic1.jpg  

C:/trial/trial1/trial11/pic2.jpg  

and

C:/trial/trial2/trial11/pic.jpg  

C:/trial/trial2/trial11/pic1.jpg  

C:/trial/trial2/trial11/pic2.jpg  

I will get the sum of the first three and the the size of the last 3 but I won´t get the size of the 6 together, if that makes sense. 我会得到前三个的总和与后三个的大小,但如果合理的话,我将不会得到六个的大小。

You are ignoring the result of the recursive call; 您将忽略递归调用的结果; fileSize is not shared between calls. 调用之间不共享fileSize

Instead of passing in fileSize to recursive calls, sum the returned sizes: 不要将fileSize传递给递归调用,而是对返回的大小求和:

def myFunction(myPath): 
    fileSize = 0

    for myfile in glob.glob(myPath): 
        if os.path.isdir(myFile):
            fileSize += myFunction(myFile)

        if fnmatch.fnmatch(myFile, '*.jpg'):
            fileSize += os.path.getsize(myFile)


    return fileSize

then print the final total returned by the outermost call: 然后打印最外层调用返回的最终总数:

print myFunction('C:/trial/')

You should use os.walk() to solve this problem. 您应该使用os.walk()解决此问题。

This is how I would do it - 这就是我的做法-

import os
import sys

def get_file_size(path, extensions):
    size = 0

    for root, dirs, files in os.walk(path):
        for file in files:
            if (file.lower().endswith(extensions)):
                size += os.path.getsize(os.path.join(root, file))

    return size

print(get_file_size('.', ('jpg', 'jpeg')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM