[Tutor] Deleting specified files using a python program...help with code?
Cédric Lucantis
omer at no-log.org
Mon Jun 30 16:50:09 CEST 2008
Le Monday 30 June 2008 16:17:45 Saad Javed, vous avez écrit :
> Here's the working code for my problem. But i tried it to post 'No
> files found' in case no specified files are found. It doesn't do that.
> Just simply exits.
>
> dir_input = raw_input('Enter dir: ')
>
> win_trace = ['*.ini', '*.db']
>
> for root, dirs, files in os.walk(dir_input):
> for trace in win_trace:
> win_trace_path = os.path.join(root, trace)
> for filename in glob.glob(win_trace_path):
> if os.path.exists(filename):
> print filename
> else:
> print 'No files found'
glob() will of course always return existing files only, so this part of the
test will never be reached, unless the file is removed by another process
between glob() and exists() which is very unlikely to happen.
> confirmation = raw_input('Confirm removal: ')
> if confirmation == 'y':
> os.remove(filename)
> print 'done'
just printing 'done' for each file won't help the user, this would be better:
print "removing '%s'" % filename
os.remove(filename)
(a confirmation after the remove() is not really necessary, as python will
raise an exception and abort the program if an error occurs)
> elif confirmation == 'n':
> pass
> else:
> sys.exit()
maybe an error message would help the user here too. sys.exit() accepts a
string argument for that: sys.exit('invalid answer'). It will just print the
message on stderr and exit with an error code.
Finally, if what you want is to print a message at the end when no file has
been processed, you can do this:
removed_files = 0
for root, dir, file in ... :
...
if confirmation == 'y' :
os.remove(filename)
removed_files += 1
...
if removed_files :
print '%d files removed' % files_removed
else :
print 'No files found'
--
Cédric Lucantis
More information about the Tutor
mailing list