HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

List files in a directory

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listdirectoryfiles

Problem

I have folder1 that contains other folders (which may contain other folders etc). This process stops at some point where a folder contains only files, and some of them end with the string "img".

I would like to write to a file for each line:

-
the complete path of the file (if ends with, say "img")

-
the immediate folder that contains it

something like

/path/start/folder1/folder2/.../folderN/file123-img folderN


My Python 3 code is

import os
file_list = []
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders == []:
            for fil in files:
                if fil.endswith('img'):
                    final = (root.split("/"))[-1]
                    fp.write(root + "/"+fil + " " + final +"\n")


I wonder if i could use more pythonic tool (like comprehensions) instead for - if - for - if

Solution


  • You do not use file_list



  • Emptiness of container (as in PEP8) is usually checked by if not container.



  • For path operations os.path is preferred. Let's change 'final' to os.path.dirname and building path to os.path.join. Avoid os-specific solutions.



  • Let's reduce indentation by using continue statement.



  • IMHO using comprehensions is not preferable here. Pythonic means 'obvious' and 'simple' way, and this is very simple way.



  • I introduced explanatory variable and tweaked naming a little bit.



  • Consider separating building file list with writing it to file. Separating responsibilities is usually great idea. If you do that maybe you'll be able to find good place to use comprehensions.



Improved code (without separating) below:

import os
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders:
            continue
        for fil in files:
            if not fil.endswith('img'):
                continue
            dir_name = os.path.basename(fil)
            full_path = os.path.join(root, fil)
            fp.write("{0} {1}\n".format(full_path, dir_name))

Code Snippets

import os
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders:
            continue
        for fil in files:
            if not fil.endswith('img'):
                continue
            dir_name = os.path.basename(fil)
            full_path = os.path.join(root, fil)
            fp.write("{0} {1}\n".format(full_path, dir_name))

Context

StackExchange Code Review Q#64196, answer score: 10

Revisions (0)

No revisions yet.