[Tutor] Deleting specified files using a python program...help withcode?

Mark Tolonen metolone+gmane at gmail.com
Sun Jun 29 18:11:29 CEST 2008


"Saad Javed" <sbjaved at gmail.com> wrote in
message news:3c10cd400806290813s6cb74717u3e86a0196c86803d at mail.gmail.com...
> I transfer files a lot between my windows and linux partitions...these 
> folders sometimes
> contain *.db and *.ini files which are not recognized or used by linux.
> So i tried to write a program to crawl through my home dir and remove 
> these files...
> I'm *very* new to programming and python so please be gentle. Here is > 
> the code:
>
> import os
>
> list = ['*.ini', '*.db']
>
> for root, dirs, files in os.walk('/home/saad'):
>
> for list in files:
>
> os.remove(os.path.join('root', 'list'))
> print 'done'
>
>
> Unfortunately its a bit too efficient and nearly wiped my home dir before 
> i manually killed it. Again...treat me like a super noob.

It's a good idea to use "print" instead of a destructive command like 
"os.remove" until print displays the correct filenames :^)
Also, "list" and "file" are Python built-ins, so avoid using those names in 
code.

  import os,fnmatch
  patterns = '*.ini *.db'.split()
  for root,dirs,files in os.walk('/home/saad'):
    for pattern in patterns:
      for file_ in fnmatch.filter(files,pattern):
        print os.path.join(root,file_)

-Mark




More information about the Tutor mailing list