Sorry if I named it wrong, this is my first try in python make some working script. I made list with Dictionary Cursor
, but I need now to work with is as variables and delete folders. For example.
If I will found in /data/system/domain.tld
and domain.tld
is listed in from my select in ["name"] I want to delete that directory. How should I proceed with my code when I want this functionality?
import pymysql.cursors
import os
connection = pymysql.connect(host='localhost',
user='root',
password='password',
db='database',
cursorclass=pymysql.cursors.DictCursor)
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 (row)
print("id = ", row["id"], )
print("name = ", row["name"])
print("state = ", row["state"], "\n")
Assuming the above syntax is working correctly, i.e. producing rows where the row[name]
values are the paths of the directories you wish to delete, then you should just need to add the delete command to your for
loop as a new line.
The above link has a lot more information on how to delete files and folders using Python. Looking at the top answer, the shutil.rmtree()
function looks like it should delete a directory based on a given path.
You can find the shutil documentation here
So, if you wanted to continue to print all those variables, your for
loop should just need the additional line with the shutil.rmtree()
function:
for row in records:
print (row)
print("id = ", row["id"], )
print("name = ", row["name"])
print("state = ", row["state"], "\n")
shutil.rmtree(row["name"])