3
\$\begingroup\$

I am using a function that returns a list of all files (full path for each of them) with the given extension in the given folder and all subfolders. As the process is quite long and user can get feeling that the app freezes, every 5 seconds I write to the output the name of the file the script is working on. The code below works fine. But I am sure it is not the most readable and effective way to write it. So I am eager for feedback and advice. Note: I tend to import as little modules as possible. os and time for this task is enough, I think.

import os
import time

def all_files_list(checkpath):
    '''Creates list of all files in subfolders of the given folder.
    Counts only .png'''
    lastTimer = time.time()
    result_list = []
    if checkpath:
        for root, dirs, files in os.walk(checkpath):
            for x in files:
                if x[-4:] == ".png":
                    if time.time() - lastTimer2 > 5:
                        lastTimer2 = time.time()
                        print('Working on ' + os.path.join(root, x))
                    result_list.append(os.path.join(root, x))
    return result_list

It creates a list of all files. Then depending on the task settings this list is filtered by specific parameters (i.e. by the language code in specific part of the path name). Then there are many options available of what can be done with the files. Copy in some structure, comparing the same files in the next folders, etc.

\$\endgroup\$
5
  • \$\begingroup\$ Please share your imports. Is there a reason you're restricted to Python 2.x? \$\endgroup\$ – Mast Mar 20 at 8:00
  • \$\begingroup\$ Sorry, I do not understand. This function is a part of a big application. Should I put here all imports that application uses? \$\endgroup\$ – SlavaB Mar 20 at 12:50
  • \$\begingroup\$ It is a part of a big project that was started with python 2.x. At the moment I think it will be more troublesome to move it to python 3 than continue using 2.7. \$\endgroup\$ – SlavaB Mar 20 at 12:52
  • 1
    \$\begingroup\$ At least all the imports that are used by this function. Can you tell us more about how this function is used in your bigger application as well? It's a lot easier to review code if the code is in it's original environment. \$\endgroup\$ – Mast Mar 20 at 13:41
  • \$\begingroup\$ It created a list of all files. Then depending on the task settings this list is filtered by specific parameters (i.e. by the language code in specific part of the path name). Then there are many options available for user of what can be done with the files. Copy in some structure, comparing the same files in the next folders, etc. \$\endgroup\$ – SlavaB Mar 20 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.