Search code examples
mysqlpython-3.xpymysql

Work with list variable in python 3 and delete folders based on it


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")

Solution

  • 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.

    Delete a file or folder

    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"])