| | |
Prevent Code Errors?
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
Here is my code:
[php]# search for a file, and show all files found in that file's directory
# delete them if wanted
import os
import pickle
def file_find(folder):
"""search for a filename fname starting in folder"""
for root, dirs, files in os.walk(folder):
for file in files:
# make search case insensitive
if fname.lower() == file.lower():
return os.path.join(root)
return None
# file to search for ...
fname = raw_input("File? ")
# folder to start search ...
folder = raw_input("Directory? ")
result = file_find(folder)
if result:
print "File found -->", result
print "\n===============================\nFollowing are the files in the same directory\n===============================\n"
directory = result
allfiles = [] #store all files found
for root,dir,files in os.walk(directory):
filelist = [ os.path.join(root,fi) for fi in files ]
for f in filelist:
allfiles.append(f)
fileAmount = len(allfiles)
for i in allfiles:
print "file ", i
print "\n===============================\n"
counter = 0
while counter != fileAmount:
showFile = allfiles[counter]
counter += 1
if counter == fileAmount:
break
deleteFiles = raw_input("Delete whole list? (y/n): ")
if deleteFiles == "Y" or deleteFiles == "y":
print "Sure?"
positive = raw_input("To delete, type: 'delete', to not delete, type anything else... ")
if positive == "delete" or positive == "Delete":
counter = 0
while counter != fileAmount:
hostageFile = allfiles[counter]
os.remove(hostageFile)
counter += 1
print "deleted",counter,"files..."
if counter == fileAmount:
break
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "File %s not found" % fname
raw_input("")[/php]
But when it is trying to delete a directory with files that wont be easily deleted, it errors and closes.
I would like to add to the code a way to tell it to skip files that don't want to be deleted, and continue deleteing other files.
[php]# search for a file, and show all files found in that file's directory
# delete them if wanted
import os
import pickle
def file_find(folder):
"""search for a filename fname starting in folder"""
for root, dirs, files in os.walk(folder):
for file in files:
# make search case insensitive
if fname.lower() == file.lower():
return os.path.join(root)
return None
# file to search for ...
fname = raw_input("File? ")
# folder to start search ...
folder = raw_input("Directory? ")
result = file_find(folder)
if result:
print "File found -->", result
print "\n===============================\nFollowing are the files in the same directory\n===============================\n"
directory = result
allfiles = [] #store all files found
for root,dir,files in os.walk(directory):
filelist = [ os.path.join(root,fi) for fi in files ]
for f in filelist:
allfiles.append(f)
fileAmount = len(allfiles)
for i in allfiles:
print "file ", i
print "\n===============================\n"
counter = 0
while counter != fileAmount:
showFile = allfiles[counter]
counter += 1
if counter == fileAmount:
break
deleteFiles = raw_input("Delete whole list? (y/n): ")
if deleteFiles == "Y" or deleteFiles == "y":
print "Sure?"
positive = raw_input("To delete, type: 'delete', to not delete, type anything else... ")
if positive == "delete" or positive == "Delete":
counter = 0
while counter != fileAmount:
hostageFile = allfiles[counter]
os.remove(hostageFile)
counter += 1
print "deleted",counter,"files..."
if counter == fileAmount:
break
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "File %s not found" % fname
raw_input("")[/php]
But when it is trying to delete a directory with files that wont be easily deleted, it errors and closes.
I would like to add to the code a way to tell it to skip files that don't want to be deleted, and continue deleteing other files.
Yes, yes you can. It has a purpose though, my computer teacher likes to mess up the games kids install in the lab, give them a challenge if they want to play, and I made this program which he can use to sometimes delete the map files or whatnot, and since it searches for a file, even if they try to hide the game, that won't help, but sometimes it will error and just stop, I want it to skip the file it can't delete and continue on.
•
•
Join Date: Oct 2006
Posts: 16
Reputation:
Solved Threads: 3
I don't have much time, so I can only really post this much. Take a look at Mouche's scheduling program:
[PHP]
def add_address(self):
try:
self.address = schedule_data[0][3]
except IndexError:
pass
try:
self.city = schedule_data[0][4]
except IndexError:
pass
try:
self.state = schedule_data[0][5]
except IndexError:
pass
try:
self.zip = schedule_data[0][6]
except IndexError:
pass
[/PHP]
IndexError can be replaced with whatever type of error you're trying to catch. Hopefully somebody else with more time can explain this more fully.
[PHP]
def add_address(self):
try:
self.address = schedule_data[0][3]
except IndexError:
pass
try:
self.city = schedule_data[0][4]
except IndexError:
pass
try:
self.state = schedule_data[0][5]
except IndexError:
pass
try:
self.zip = schedule_data[0][6]
except IndexError:
pass
[/PHP]
IndexError can be replaced with whatever type of error you're trying to catch. Hopefully somebody else with more time can explain this more fully.
Here is a list of all the built-in errors to "except" using the try-except statements:
http://www.python.org/doc/2.4.1/lib/...xceptions.html
But, the easiest thing to do is run your code in a way that you can see the traceback errors. It will say something like "IndexError." Then just write whatever you want to do under the "try:" and then below it write an "except IndexError:", which executes if the code under the "try:" gets an error. Like Zonr said, you replace "IndexError" in my example with whatever error is shown by the traceback errors.
http://www.python.org/doc/2.4.1/lib/...xceptions.html
But, the easiest thing to do is run your code in a way that you can see the traceback errors. It will say something like "IndexError." Then just write whatever you want to do under the "try:" and then below it write an "except IndexError:", which executes if the code under the "try:" gets an error. Like Zonr said, you replace "IndexError" in my example with whatever error is shown by the traceback errors.
![]() |
Similar Threads
Other Threads in the Python Forum
- Previous Thread: Event handling across panels issues...
- Next Thread: Color Dictionary
| Thread Tools | Search this Thread |
accessdenied advanced application argv beginner change color command convert csv cursor def dictionary digital dynamic dynamically edit editing enter event examples excel file float format frange function google gui homework i/o import input jaunty java keyboard lapse line linux list lists loop microphone mouse movingimageswithpygame newb number numbers numeric obexftp output parameters parsing path port prime programming projects py2exe pygame pygtk pyopengl python random recursion remote return reverse scrolledtext session simple skinning smtp sprite stderr string strings subprocess syntax table tennis terminal text thread threading time tkinter tlapse tuple tutorial ubuntu unicode unit urllib urllib2 variable voip web-scrape windows wxpython






