[Tutor] Dos and os.walk with Python

Alan Gauld alan.gauld at btinternet.com
Fri Jan 25 02:11:00 CET 2008


"Timothy Sikes" <trs164 at hotmail.com> wrote

>  I don't know if it's okay to ask about Dos in python mailing list,

If its related to programming in python as well its fine :-)

> I don't know if there are any formatting rules for posting programs

It helps if we can see the formatting, especially since Python
relies on  layout. This was just a mess on my screen!

I've tried to sort it out...

---------------------------------------
import os, sys, time

def earlierThan (path, year, exclude=[]):
    all = []
    walk = os.walk(path)
    for root, dirs, files in walk:
        for i in files:
            try:
                if (time.localtime(os.path.getmtime(root + "\\" + 
i))[0] < year
                    and doesNotHave(exclude, root)) :
                    all.append(root + "\\" + i)
            except OSError:
                 #I think that I might need a more specific error 
message,
                 #as this one would handle something
                 #That's not necessarily a broken file name. (I got 
one of them when I ran it).
                 print root + "\\" + i + " was not included in the 
list"
    return all

def doesNotHave(exclude, root):
    for x in exclude:
        if root.startswith(x) > -1:
            return False
    return True
----------------------------------------------

That last function is a little odd. startswith already returns
a boolean so comparing to -1 is weird. I'm not sure what
you think it will do.

Consider:

>>> 'fred'.startswith('x')
False
>>> 'fred'.startswith('x') > -1
True
>>> 'fred'.startswith('f') > -1
True
>>>

I'm not sure when it would ever fail the test so I think your
function will nearly always return False.

> I've had little experience with dos.  I believe I should use the
> COMPACT, and then the MOVE dos command... Would
> it go something like this?

You could use these but you'd be better just using Python
to do it via the shutil and os modules and avoid the DOS
commands completely IMHO.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list