[Tutor] annoying directory structure

Zachary Ware zachary.ware+pytut at gmail.com
Sat Apr 11 02:14:16 CEST 2015


On Thu, Apr 9, 2015 at 10:07 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
[Previously, I wrote:]
>> I'll need to see some actual code (namely, where and how you used
>> os.walk) to have any real idea of what's going on. The online docs for
>> os.walk have a pretty good explanation and example.
>
>
> This worked. I didn't know why I got doubled strings, but print
> concatenated them so I printed to a file, and the text lines all open an
> mp4 in windows explorer, as expected. Unfortunately they aren't in order,
> so I guess I'll have to actually read up on walk. I just wanted to knock it
> out quickly by figuring out the walk output format, and get on with the
> course ;')
>
> tutfiles = open('tutfiles.txt', 'w')
> p = os.walk('I:\\VIDS\\Learn Python Track\\')
> for triplet in p:
>     if triplet[2] == []:
>         continue
>     else:
>         if 'mp4' in triplet[2][0]:
>             print(triplet[0] + '\\' + triplet[2][0], file=tutfiles)
>
> tutfiles.close()

Frankly, that's a bit horrifying :).  I'm glad you came up with a
solution that works for you using the tools available to you, but it's
far from idiomatic Python code.

Here's how I would write it (please excuse any syntax errors; I'm not
testing it.  Logic errors, I'll take the blame :) ).

"""
import os

def get_filenames(top_level_dir):
    all_video_files = []
    for dir, dirs, files in os.walk(os.path.abspath(top_level_dir)):
        for filename in files:
            if filename.endswith('.mp4'):
                all_files.append(os.path.join(dir, filename))
    return all_video_files

print(*get_filenames("your root directory"), sep='\n')
"""

If you need them sorted in some particular way, you can sort the list
before printing it, using the sort() method of the list (and probably
the 'key' keyword argument).

Please take a look at this and try to understand what it's doing, and
ask about anything that doesn't make sense (that's the most important
part!).

Hope this helps,
-- 
Zach


More information about the Tutor mailing list