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