1

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")
Delirium
  • 1,277
  • 3
  • 16
  • 27

3 Answers3

3

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")
Artiom Kozyrev
  • 3,526
  • 2
  • 13
  • 31
  • `try-except` is actually better to avoid a race condition, see https://stackoverflow.com/questions/14574518/how-does-using-the-try-statement-avoid-a-race-condition – Chris_Rands Oct 21 '19 at 14:11
  • 1
    @Delirium there are many options to combo conditions first option is ```if state == 2 and os.path.exists("some path"): your code```, another option is to put ```if os.path.exist("some path")``` inside ```if state == 2:``` – Artiom Kozyrev Oct 21 '19 at 14:12
1

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:
Sreejith
  • 434
  • 3
  • 19
0

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)
Fabio Caccamo
  • 1,871
  • 19
  • 21