Reputation: 1577
I am selecting datas from my database, and deleting inactive domains from my filesystem. Sometime, I have domain, which was deactivated twice in database, script will try to delete it also twice, since it's going for each row.
How to fix the issue, when script will find hosting in database, which was on filesystem already deleted, so it will check it's deleted and will continue and not crash on
os.rmdir('/data/sa/' + name)
FileNotFoundError: [Errno 2] No such file or directory: '/data/sa/test3.com'
masir@linux-hjay:~/Documents/python> ls /data/sa/
Here is my code:
cursor = connection.cursor()
sql="SELECT id, name, state FROM domain WHERE state='2'"
cursor.execute(sql)
records = cursor.fetchall()
print("Total number of records for deleting is: ", cursor.rowcount)
print("\nPrinting each domain record")
for row in records:
print("id = ", row["id"], )
print("name = ", row["name"])
print("state = ", row["state"], "\n")
id = row["id"]
name = row["name"]
state = row["state"]
if state == 2:
# print(state)
print('found records for deleting' + name)
os.rmdir('/data/sa/' + name)
else:
print('no records for deleting found')
print('domain', name)
print('hast state', state, "\n")
Upvotes: 1
Views: 1117
Reputation: 1971
I suggest you to use shutil
to remove folders:
import os, shutil
try:
shutil.rmtree(path)
print('folder removed')
except Exception as e:
print('folder not removed')
print(e)
Upvotes: 0
Reputation: 464
You can use try/except for this as below, so that script will not get failed at the deleting step.
if state == 2:
try:
# print(state)
print('found records for deleting' + name)
os.rmdir('/data/sa/' + name)
except Exception as error:
print("Directory already deleted")
else:
Upvotes: 1
Reputation: 3826
You can do the following to check if file/folder exists before trying to remove it:
import os
if os.path.exists("some path"):
pass
# remove dir
else:
print("The dir does not exist")
Upvotes: 3