woooee 814 Nearly a Posting Maven

range([start,] stop[, step]) -> list of integers
I'm just guessing but the definition would have to be something like this, although the actual code may be in C/C++

def range_test(*args_in):
   if len(args_in) == 1:
      stop=int(args_in[0])
      start=0
      step=1
      print "one arg found", start, stop, step
   else:
      ## compare for length==2 and then 3 (error if < 1 or > 3)
      print len(args_in), "args found -->", args_in

range_test(3)
range_test(1,3)
range_test(2,10,2)
woooee 814 Nearly a Posting Maven

Take a look at the control variables section at the following link. A control variable can be linked to several widgets and will update the widget automatically. http://infohost.nmt.edu/tcc/help/pubs/tkinter/

woooee 814 Nearly a Posting Maven

I know nothing about twill, but find "EMail" in what? You would also have to give it a file name or a string, etc. to search in. You would want to tell it if you want a search or a match as well. Looks like Google time. Also, see if Twill has a forum or mailing list that you can search.

woooee 814 Nearly a Posting Maven

And if you are using a list, then the individual variable for each random number isn't necessary.

computer_list = []
for j in range(0, 4):
   computer_list.append(random.randint(0, 30))
print "The computer's numbers are", computer_list
#
#
#    To enter all 4 numbers on one line, use the split method
numbers = raw_input("Enter 4 numbers between 0-30 separated by a space ")
numbers_list = numbers.split()
if len(numbers_list) != 4:
   print "4 numbers were not entered"
else:
   lit = "Loser"
   for number in numbers_list:
      if int(number) in computer_list:
         lit = "You found number " + number
   print lit
woooee 814 Nearly a Posting Maven

I would do something like this. Note that in your original code, the first word, "God", would never be found because you don't allow for a4==0.

a1="God Godess Borother Sister Family DemiGod" 
a1_list=a1.lower().split() 
a5=[]
input_word=raw_input("PRINT A WORD ") 
for each_word in a1_list:
   if input_word in each_word:
      a5.append(each_word)
print a5
woooee 814 Nearly a Posting Maven

You may also want to look at the radiobutton widget. A slight modification of one of Grayson's examples

from Tkinter import *

root = Tk()
root.title('Radiobutton')

fruit=[('Passion fruit\nSecond line', 1), ('Loganberries', 2), 
        ('Mangoes\nin syrup', 3), ('Oranges', 4), 
        ('Apples', 5), ('Grapefruit', 6)]
var = IntVar()
for text, value in fruit:
    Radiobutton(root, text=text, value=value, variable=var).pack(anchor=W)
var.set(3)
root.mainloop()
woooee 814 Nearly a Posting Maven

Unfortunately, threading or pyprocessing if the only way that I know http://pyprocessing.berlios.de/doc/index.html

woooee 814 Nearly a Posting Maven

You can use sys.path.append() in each program to append to the PYTHONPATH if that is what you mean. It is difficult to understand what is going on without code. If this does not answer your question please post some example code or pseudo-code with an explanation of what each program is to do regarding sys.

woooee 814 Nearly a Posting Maven

Generally, /python/site-python is used for individual packages. You may have to create the directory, but then could place your other directories under this one, and assuming the system knows where /python is, you could then add the path /python/site-python to $PYTHONPATH or just append your other directories to sys.path.

woooee 814 Nearly a Posting Maven

I don't use Tkinter but it doesn't print because the function "check()" has no idea what type1 is. Run the code below. I have changed check() so that it just prints "type1". It now knows what to print and so you get some output. I think you have to use a control variable in Tkinter to get the state of a radio buttion(s). If you are going to be passing variables around in a Tkinter program, I would suggest using a class.

from Tkinter import *
root = Tk()
root.geometry("120x100+15+15")

output = file('robot_info.txt', 'a')

def check():
   print "type1"
 
v=StringVar()
COLOR = [("Blue", "Blue"), ("Red", "Red"), ("White", "White")]
v.set("Blue")

for text, type1 in COLOR:
   b = Radiobutton(root, text = text, variable = v, value = type1, indicatoron=1,   command=check)
   b.pack(anchor = W)

root.mainloop()
woooee 814 Nearly a Posting Maven

It appears from your code that MS Access is SQL. If so, you can use ORDERBY. A Google for "access orderby" should get you started.

woooee 814 Nearly a Posting Maven

getch in Python is not easy. One implementation found on the web uses termios

import termios, sys, os                                                         
TERMIOS = termios                                                               
def getkey():                                                                   
        fd = sys.stdin.fileno()                                                 
        old = termios.tcgetattr(fd)                                             
        new = termios.tcgetattr(fd)                                             
        new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO                       
        new[6][TERMIOS.VMIN] = 1                                                
        new[6][TERMIOS.VTIME] = 0                                               
        termios.tcsetattr(fd, TERMIOS.TCSANOW, new)                             
        c = None                                                                
        try:                                                                    
                c = os.read(fd, 1)                                              
        finally:                                                                
                termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)                   
        return c                                                                
                                                                                
if __name__ == '__main__':                                                      
        print 'type something'                                                  
        s = ''                                                                  
        while 1:                                                                
                c = getkey()                                                    
                if c == 'q':                                                    
                        break                                                   
                print 'got ("q" = end)', c                                      
                s = s + c                                                       
                                                                                
        print s
woooee 814 Nearly a Posting Maven

You can put as many lines as you want into a listbox. If there are more lines than the listbox will display, then you also want to add a scrollbar.

import Tkinter                                                                  
                                                                                
top = Tkinter.Tk()                                                              
top.geometry( "100x100+10+10" )                                                 
top.minsize( 200, 200 )                                                         
                                                                                
listbox = Tkinter.Listbox( top, height=6, width=20, font=('Fixed', 14) )        
scrolly = Tkinter.Scrollbar( top, command=listbox.yview )                       
listbox.configure(yscrollcommand=scrolly.set)                                   
                                                                                
scrollx = Tkinter.Scrollbar( top, orient=Tkinter.HORIZONTAL, command=listbox.xvi
listbox.configure(xscrollcommand=scrollx.set)                                   
                                                                                
lit = [ "aaa", "bbbbb", "ccccccc", "dd", "e", \                                 
        "fff", "ggggg", "hhhhhhh", "jj", "m", "nn" ]                            
for item in range(10):                                                          
    this_lit = lit[item]                                                        
    new_item = "%(item)d  %(this_lit)-10s  %(this_lit)-10s  %(this_lit)-10s" % v
    listbox.insert(Tkinter.END, new_item)                                       
                                                                                
cont = Tkinter.Button(top, text='CONTINUE',                                     
       command=top.quit, bg='red', fg='white' )                                 
cont.pack(side="bottom", fill=Tkinter.X, expand=1)                              
scrolly.pack(side="right", fill="y")                                            
scrollx.pack(side="bottom", fill=Tkinter.X, expand=1)                           
listbox.pack(side="left")                                                       
                                                                                
top.mainloop()
woooee 814 Nearly a Posting Maven

Use a dictionary with the key="ABCD". If the key is found in the dictionary compare the values. If the current rec has a lower value, replace the rec for that dictionary item.

woooee 814 Nearly a Posting Maven

I would do it in a similiar way. Provided all of the pages can be stored in memory, the following creates a junk_list that stores pages until the next "ND" is found. It then prints the first and last pages in junk_list and blanks junk_list. You could also store the first page and previous record in variables and print them when "ND" is found. Using lists is the easier way but does take more memory.

test_data = [
"Page1,ND\n",
"Page2,\n",
"Page3,\n",
"Page4,ND\n",
"Page5,\n" ]

junk_list=[]
for rec in test_data:
   substrs = rec.strip().split(",")

   if len(substrs) > 1:
      if (substrs[1].strip()=="ND") and (len(junk_list)):
         print "pages =", junk_list[0], junk_list[-1]
         junk_list=[]
   junk_list.append(substrs[0])

##--- final group of pages
print "pages =", junk_list[0], junk_list[-1], "final group"
woooee 814 Nearly a Posting Maven

There is no way to tell without code and a complete message but "AttributeError: 'ShortAnswerQuestion' object has no attribute 'question_id' " usually applies to a class (don't know if you use one or not). So instead of declaring a variable as self.question_id, it is defined as question_id and so is not a member of the class but is a member of the function that declares the variable.

woooee 814 Nearly a Posting Maven

What you have done is the easiest way to do it because you have control. Remember that you have to parse the string no matter what the method. Even when Python has a method to do it, the string still has to be parsed, so you should have no problem with doing it yourself. It would be slightly more efficient to find the second "\" and slice there, but is more trouble than it is worth.

woooee 814 Nearly a Posting Maven

line = file.readline() reads to the end of the file and then stops. Adding a "print line" statement after each readline[s] is the best way to tell what is going on.

woooee 814 Nearly a Posting Maven

You can do this using sys.argv - use
getDirPath.py 'mypath'
and inside the program
print sys.argv, type(sys.argv)

As for drag and drop, Python is geared more towards a GUI, so you want FileDialog in Tkinter or QFileDialog in qt and the wx tool kit probably has something similiar, to select the file and pass the name to the program.

woooee 814 Nearly a Posting Maven

You can use the split() method.
substrs=line.split()
if (substrs[0]=="call") and (substrs[1].startswith("%"):
You will probably have to check for a length of 2 or more and may want to convert to lower case before comparing to "call", but that is the general idea.

woooee 814 Nearly a Posting Maven

Not exactly a quote, but the first announcement that Microsoft was trying to buy Yahoo for 30+ billion, was followed here in SoCal by the story that Exxon-Mobil reported a profit for the year of 40+ billion. I hope it was intentional.

woooee 814 Nearly a Posting Maven

unicode characters are being interpreted as two characters rather than one

This usually means that it is not a unicode string, but a standard python string. In 3.0, all strings will be unicode by default, so I have heard, and so will not require conversion. Look at the print out from the following snippet. I am not even close to being an expert on unicode, but I think this will work.

normal_string='ÂBÇD'                                                                       
for chr in normal_string:
   print ord(chr),
   print "\n--------------------"
#
##unicode_string=u'ÂBÇD'     ## use this or the following line
unicode_string=normal_string.decode('utf-8')
print "\n"
for chr in unicode_string:
   print ord(chr)
   print "--------------------"
woooee 814 Nearly a Posting Maven

out_file = open("address.txt", "w")

Change this to
out_file = open("address.txt", "a")
You want to "a"=append to, not "w"=write over. And to start you out

if choice == 2:
    in_file = open("address.txt", "r")
    text = in_file.readlines()
    in_file.close()
    print text
woooee 814 Nearly a Posting Maven

If there are a lot of words to look up, use sets. They are indexed and are much faster than a list.
reference_list=[ "AA", "AB", "BB", "AC", "BC" ]
ref_set=set(reference_list)
lookup_set=set(["AB", "BB", "CC"])
print lookup_set.intersection(ref_set)
print lookup_set.difference(ref_set)

woooee 814 Nearly a Posting Maven

For completeness, list comprehension
string="airplane"
now_a_list=[x for x in string]

woooee 814 Nearly a Posting Maven

I don't use Tkinter much, but AFAIK you have to use threading for something like this. A simple example from effbot http://effbot.org/zone/tkinter-threads.htm

woooee 814 Nearly a Posting Maven

A similiar question was recently asked. See if this helps.
http://www.daniweb.com/forums/thread128927.html

woooee 814 Nearly a Posting Maven

Doug Hellman's module of week shows how to read output, and use stdin, stdout, stderr. Don't know if it will solve your problem or not, but if you can read it you can write to a file, send e-mail, etc. Some systems buffer the output, so you may have to turn buffering off for the thread in order to read it as it is generated. There is pyprocessing also which has shared objects. I have not used it though.
http://blog.doughellmann.com/2007/07/pymotw-subprocess.html
http://pyprocessing.berlios.de/

woooee 814 Nearly a Posting Maven

It's just personal preference, but I prefer to work with numbers in this type of code. So the following is an example of using the ord() of the character as the key in a conversion dictionary.

#!/usr/bin/python
# -*- coding: utf-8 -*-

x_list=[u'Ä', u'Â']
print ord(x_list[0]), ord(x_list[1])

ord_dic={194:'A', 196:'A', 197:'A', 199:'C'}
for chr in x_list:
   if ord(chr) in ord_dic:
      print ord(chr), 'converts to', ord_dic[ord(chr)]

print
x=u'ÂBÇD'
new_str=""
for chr in x:
   ord_chr=ord(chr)
   if ord_chr in ord_dic:
      print ord_chr, 'converts to', ord_dic[ord_chr]
      new_str += ord_dic[ord_chr]
   else:
      new_str += chr
print "converted to", new_str
woooee 814 Nearly a Posting Maven

The dictionary principle remains the same. It doesn't matter if there are multiple words or just one word.
dictionary key = what is in file = Store2 "Soap of Marseille" --> look up "Soap of Marseille"
so store_dic["Soap of Marseille"] = "SOM"
If you are unsure of punctuation, use isalpha to eliminate spaces, etc for both the key and the look up phrase.
To print the dictionary:
.for key in store_dic.keys():
......print store_dic[key], key --> "SOM Soap of Marseille"
If this doesn't explain it, post your code. It is more difficult to explain in the abstract.

woooee 814 Nearly a Posting Maven

A few print statements should simplify things

import sys

##python ./myScript.py -b -e 'test_name'
print sys.argv, "\n"
file_found=0
for j in range(1, len(sys.argv)):
   print " arg", j, sys.argv[j]
   if not sys.argv[j].startswith("-"):
      print "     name is", sys.argv[j]
      file_found=1
if (" -c" not in sys.argv) and (" -u" not in sys.argv):
   print "\n no -c or -u arg found"
if not file_found:
   print "\n no file name arg found"
woooee 814 Nearly a Posting Maven

You could also replace the following:

reducedList = [n for n in listParagraph if len(n) == len(word)]
## replace with this
reduced_list = [n for n in list_paragraph if word == n.lower()]
if len(reduced_list):
    print "The word", "'" + word + "'", "occurs", len(reduced_list), "times in this section."
else:
    print "The word", "'" + word + "'", "does not occur in this section of text."
#
# anyway, here is another solution
#
paragraph = '''This is a test sentence.  We will look for hi in this sentence.
If we find 'hi', we want to keep count of it.  Remember, hi
can be Hi or hi.  Hi can also have characters before or
after it ie (hi. hi, hi:).  There should be a total of 10 'hi'
in this sentence, not any more for words like 'this' or
'hippo' or 'hiccups' '''

word='hi'
p_list = paragraph.split()
ctr=0
for p_word in p_list:
   p_word = p_word.lower()
   if p_word == word:
      ctr += 1
   elif not p_word.isalpha():     ## has non-alpha characters
      new_word = ""
      for chr in p_word:
         if chr.isalpha():
            new_word += chr
      if new_word == word:
         ctr += 1
print "The word '%s' was found %d times" % (word, ctr)
woooee 814 Nearly a Posting Maven

Sorry for the late post. I just noticed this. Your button line should read
self.connect(button, SIGNAL("clicked()"), self, SLOT("close()"))
I'm thinking of doing a PyQt tutorial, or at least a list to links on using PyQt(4), thread on DaniWeb. Do you have any links that might be of interest?

woooee 814 Nearly a Posting Maven

And for completeness, creating a second list of lists, with the int as the first element so you can use Python's built in sort.

##   simulate reading data from file
data = [ "ABGH SDFDS 123\n", "SDFS sDF 12\n", "DEF SDFDS 124\n",
         "ABGH SDFDS 2\n", "SDFS sDF 10\n", "DEF SDFDS 100\n",
         "DEF SDFDS 1\n"]

sort_list = []
for rec in data:
   substrs = rec.split()
   sort_list.append( [int(substrs[2]), rec] )

print "sort_list original =", sort_list
sort_list.sort()
print "\nsort_list sorted =", sort_list
woooee 814 Nearly a Posting Maven

I guess the above example can appear obfuscated to some, so here is another sort. This sorts the number as an integer, not a string.

##   simulate reading data from file
data = [ "ABGH SDFDS 123\n", "SDFS sDF 12\n", "DEF SDFDS 124\n",
         "ABGH SDFDS 2\n", "SDFS sDF 10\n", "DEF SDFDS 100\n",
         "DEF SDFDS 1\n"]

stop_k = len(data)
stop_j = stop_k - 1
for j in range(0, stop_j):
   rec=data[j]
   substrs = rec.split()
   lowest = int(substrs[2])  ## lowest number so far
   print "starting rec is", lowest, substrs
   ctr = j  ## contains the element number of the smallest value
   for k in range(j+1, stop_k):
      rec=data[k]  ## check the next rec until the end
      substrs = rec.split()
      this_test = int(substrs[2])
      print "   comparing", lowest, this_test
      ## data sorted as an integer
      if this_test < lowest:
         ctr=k  ## store lowest element's number and swap after all recs have been checked
         lowest = this_test ## this will now be compared to whatever recs are left
   ## swap the values once after all comparisons have been made
   if j != ctr:
      data[j], data[ctr] = data[ctr], data[j]

print "\n", data
woooee 814 Nearly a Posting Maven

Total price would be a separate variable that you add price to. If you want to process more than one person at a time and give a grand total, there would have to be a while loop somewhere in the program.

woooee 814 Nearly a Posting Maven

Although I don't use wxPython, you should be able to use a dictionary to clean up the code. Something like this. Again I don't use this toolkit so it may require tuning.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 350))

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        panel1 = wx.Panel(self, -1)
        panel2 = wx.Panel(self, -1)

        self.tree = wx.TreeCtrl(panel1, 1, wx.DefaultPosition, (-1,-1), 
                                   wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS)
        root = self.tree.AddRoot('Programmer')
        os = self.tree.AppendItem(root, 'Operating Systems')
        pl = self.tree.AppendItem(root, 'Programming Languages')
        tk = self.tree.AppendItem(root, 'Toolkits')

        root_dict = {}
        root_dict[os] = ('Linux',  'FreeBSD', 'OpenBSD', 'NetBSD', 'Solaris')
        root_dict[tk]  = ('Qt', 'MFC', 'wxPython', 'GTK+', 'Swing')
        for index in root_dict.keys():
           for item in root_dict[index]:
              self.tree.AppendItem(index, item)

        cl = self.tree.AppendItem(pl, 'Compiled languages')
        sl = self.tree.AppendItem(pl, 'Scripting languages')
        pl_dict = {}
        pl_dict[cl] = ('Java', 'C++', 'C', 'Pascal')
        pl_dict[sl]  = ('Python', 'Ruby', 'Tcl', 'PHP')
        for index in pl_dict.keys():
           for item in pl_dict[index]:
              self.tree.AppendItem(index, item)

        self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)
        self.display = wx.StaticText(panel2, -1, '',(10,10), style=wx.ALIGN_CENTRE)
        vbox.Add(self.tree, 1, wx.EXPAND)
        hbox.Add(panel1, 1, wx.EXPAND)
        hbox.Add(panel2, 1, wx.EXPAND)
        panel1.SetSizer(vbox)
        self.SetSizer(hbox)
        self.Centre()

    def OnSelChanged(self, event):
        item =  event.GetItem()
        self.display.SetLabel(self.tree.GetItemText(item))

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'treectrl.py')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()
woooee 814 Nearly a Posting Maven

If you just want to display the pictures, use the Python Imaging Library (PIL). http://www.pythonware.com/library/pil/handbook/index.htm

woooee 814 Nearly a Posting Maven

Add some print statements. And I've formated your snippet with code statements in the way that I think it would have to be indented, but there is no way to tell.

def divide(dividend, divisor):
   n = dividend - divisor
   print "n =", n
   while n > 0:
      print "entering while statement"
      return
woooee 814 Nearly a Posting Maven

You can split and create new list with the numbers as the first part of the rec and then use the builtin sort method, or convert to a list of lists as below. Whichever is easier in this case.

data_as_lists = [ line.strip().split() for line in data ]     ## convert to a list of lists
data_as_lists.sort(key=operator.itemgetter(-1))  ## sort on last element
for el in data_as_lists :            ## print each item in the list
   print el
sneekula commented: nice code +4
woooee 814 Nearly a Posting Maven

Add "Solved" or "Ignore This" to the thread title and in a day or two it will be too far down the list to notice.

woooee 814 Nearly a Posting Maven

You want to search for wxpyton file dialog
http://www.wxpython.org/docs/api/wx.FileDialog-class.html

woooee 814 Nearly a Posting Maven

Use the datetime module. Note that using the separate variable, start_time, is not necessary.
start_time = datetime.datetime(2008, 06, 03, 12, 30, 00)
diff_time = datetime.datetime(2008, 06, 03, 12, 50, 00) - start_time
print diff_time.seconds, type(diff_time)
print "duration in minutes =", diff_time.seconds/60
http://effbot.org/librarybook/datetime.htm
http://blog.doughellmann.com/2008/03/pymotw-datetime.html

woooee 814 Nearly a Posting Maven

Start with defining the public and private members. You should also read your own post. There is duplication re defining the class named "Corvette". Rework it so that things are clear and only defined once.

woooee 814 Nearly a Posting Maven

"Bold" is a function of the program displaying the text. In postscript it is
/Helvetica-Bold findfont % Get the basic font
11 scalefont % Scale the font
setfont % Make it the current font
You can use this if you are printing the file to a printer. For a word processor it would be different for each one, unless they use the same encoding. So insert whatever defines "bold" for the app that you are using to display the file, and then undefine bold after the word or define regular font to return to normal.

woooee 814 Nearly a Posting Maven

if file_nm.endswith(".dbf") # assumes no dirs end with dbf
requires a colon at the end
if file_nm.endswith(".dbf"):

recs = read_file_recs_using_dbfpy(file_nm)
is just a pseudo-code statement for any routine that will read the dbf file and return the data in some form that can be used by the program.

woooee 814 Nearly a Posting Maven

Sorry, I meant slice, rec[begin:end], not rec.split(). Also, you possibly want a separate program file for 'read the dbf' and then would import it into 'read the XML' to keep it from getting too confusing as can happen when everything is in one file.

woooee 814 Nearly a Posting Maven

By simply adding the extra print statements

That solves a lot of problems. You can also use os.path.walk with a callback.

def processDirectory ( args, dirname, filenames ):                              
    print 'Directory',dirname                                                   
    for filename in filenames:                                                  
       print '     File',filename                                               
                                                                                
top_level_dir = "/usr/local"                                                    
os.path.walk(top_level_dir, processDirectory, None )                            
                                                                                
##os.path.walk() works with a callback: processDirectory() will be              
##called for each directory encountered.
woooee 814 Nearly a Posting Maven

I have a .dbf file which contains three fields: an id (1), a Mapsheet # (455626) and finally a Mapsheet Name that corresponds to the Mapsheet# ( Big Lake ).

I assume you are using something like dbfpy to read the file, so populating the dictionary would be fairly simple. The following is just pseudo code.

import os

class test_class:
   def __init__(self, dbf_dir):
      self.map_dic={}
      file_names = os.listdir(dbf_dir)
      for file_nm in file_names:
         if file_nm.endswith(".dbf")     ## assumes no dirs end with '.dbf'
            self.read_dbf(file_nm)
      print self.map_dic()

   def read_dbf(self, file_nm):
      recs = read_file_recs_using_dbfpy(file_nm)
      for rec in recs:
         mapsheet_name = rec[1]     ## or whatever the form
         mapsheet_num = rec[3] 
         self.map_dic[mapsheet_num] = mapsheet_name

TC=test_class( "dbf_dir_name" )

What I want to do is read in each .xml file, search for this line:
<title Sync="TRUE">4555626.tif</title>
And replace the 4555626.tif text with the matching record from the .dbf table - (Big Lake)

So you want to use rec.find('<title Sync="TRUE">') and rec.find("</title>"). If both are found then this is the correct record and you can then calculate the beginning and end positions for a rec.split(). You can then look the number up in self.map_dic and use the corresponding name.

woooee 814 Nearly a Posting Maven

This will traverse all of the subdirectories and do what I think you want it to do. I have added some print statements which is probably enough by itself to answer your question as is shows what the root, dirs, and files contain. If you want to limit it to 3 levels, then you will want to store root and the first 2 dirs and pass them as basedir and then just use the files for that particular directory. If you are on a Linux system, pipe the output to a file if there are a lot of files and dirs. It will be easier to read. There are other ways of doing this using an os.path.walk() callback but I assume you want to continue down this road as you are following the book.

import os, os.path, stat, time
from datetime import date, timedelta

dirsNotUsed = []
def getdirs(basedir, age):
    for root, dirs, files in os.walk(basedir):
        print "root =", root
        print "dirs =", dirs
        print "files =", files

        found = 1
        for file in files:
           found_file = datecheck(root, file, age)
           if not found_file :             #At least one file is not old enough
               found = 0

           """ or backup all of the files that are old enough
           if found_file:
              backup_list.append(os.path.join(root, file))
           """

        if found:
           archive(root, files)

def datecheck(root, file, age):
    basedate = date.today() - timedelta(days=age)
    fname = os.path.join(root, file)
    used = os.stat(fname).st_mtime    # st_mtime=modified, st_atime=accessed
    year, day, month = time.localtime(used)[:3]
    lastused = date(year, day, month)
    if lastused < basedate:             #Gets …