Reputation: 25554
I'm building a simple function that works (delete the files). But In the end I want to return the list of the files that were effectively deleted.
This is the function:
def deleteFiles(files):
# empty list
RemovedFiles = list()
for file in files:
# Delete the file
if os.remove(file):
RemovedFiles.append(file)
return RemovedFiles
I run this function with:
print deleteFiles([/home/xyz/xyz.zip])
This effectively deletes the xyz.zip but returns an empty list: []
. What am I doing wrong here?
Upvotes: 2
Views: 1284
Reputation: 2991
That is because os.remove() does not return anything. Your if condition evaluates to false.
Try this:
def deleteFiles(files):
# empty list
RemovedFiles = list()
for file in files:
# Delete the file
try:
os.remove(file)
RemovedFiles.append(file)
except OSError:
continue
return RemovedFiles
This should work
Upvotes: 2
Reputation: 212855
The problem is that os.remove
does not return anything.
You can however try
and except
:
for filename in filenames:
try:
# try to remove the file
os.remove(filename)
except OSError:
pass
# file not removed (maybe does not exist or is write-protected)
# you may report an error here
else:
# this executes only if os.remove was successful
RemovedFiles.append(filename)
Upvotes: 4
Reputation: 336138
os.remove()
doesn't return a value, so your if
statement becomes effectively
if None:
RemovedFiles.append(file)
On the other hand, it does throw an exception if it can't remove the file, so the following should work:
try:
os.remove(file)
except OSError:
pass
else:
RemovedFiles.append(file)
Upvotes: 3
Reputation: 6695
os.remove() returns None, so you never get to append to the list.
Upvotes: 3