[Tutor] Using os.path.walk

Kushal Kumaran kushal.kumaran+python at gmail.com
Thu Jun 23 07:19:53 CEST 2011


On Thu, Jun 23, 2011 at 9:02 AM, Becky Mcquilling
<ladymcse2000 at gmail.com> wrote:
> I have a bunch of files I need to remove in dirs and subdirs when they are
> older than 7 days.
> I was looking at os.path.walk, to recurse the directories, but I'm having
> some difficulties with getting it to return the directory names or find
> examples of it's use for something like this.
> So far, I am trying to get it to just list the files in the directories and
> subdirs as such:
> def file_list(a, dir, files):
>   print (dir):
> os.path.walk('/etc', dir_list, None)
> Ultimately, I want it to find to stat mtime and just list, then remove the
> files and directories, older than the seven days, but I can't seem to get
> past just returning a list of files correctly.
> Are there some clear examples that someone can point me to?
> Becky

os.path.walk is deprecated in favour of os.walk.  There are a couple
of examples[1] in the documentation. The second example shows how to
remove everything under a directory.  You should be able to modify it
to remove files that satisfy your criteria.  The os.path.getmtime
function[2] gets the mtime of a file.

[1] http://docs.python.org/library/os.html#os.walk

[2] http://docs.python.org/library/os.path.html#os.path.getmtime

<snipped output>

-- 
regards,
kushal


More information about the Tutor mailing list