[Tutor] Deleting specified files using a python program...help with code?
Cédric Lucantis
omer at no-log.org
Sun Jun 29 17:55:37 CEST 2008
Le Sunday 29 June 2008 17:13:34 Saad Javed, vous avez écrit :
> 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.
>
Hum, just a little tip first: create a dummy file hierarchy to test your
program, and only run it on your home when you're sure it will work. Of
course backing up your home dir might help too :)
You're removing all files found by walk() without checking if they match the
patterns in list, so your script just removes every files under /home/saad.
I'd suggest something like this:
import os
import glob
input_dir = '...'
pattern_list = ['*.ini', '*.db']
for root, dirs, files in os.walk(input_dir) :
for pattern in pattern_list :
full_pattern = os.path.join(root, pattern)
for filename in glob.glob(full_pattern) :
os.remove(filename)
or you can do something similar with the fnmatch module. See
http://docs.python.org/lib/module-glob.html
http://docs.python.org/lib/module-fnmatch.html
--
Cédric Lucantis
More information about the Tutor
mailing list