首页 > 解决方案 > 在 python 3 中使用列表变量并基于它删除文件夹

问题描述

抱歉,如果我命名错误,这是我第一次尝试在 python 中制作一些工作脚本。我用 列出了列表Dictionary Cursor,但我现在需要将其作为变量并删除文件夹。例如。

如果我会在 ["name"] 中的选择中找到/data/system/domain.tlddomain.tld在其中列出,我想删除该目录。当我想要这个功能时,我应该如何处理我的代码?

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

标签: mysqlpython-3.xpymysql

解决方案


假设上述语法工作正常,即生成row[name]值是您希望删除的目录的路径的行,那么您只需将删除命令for作为新行添加到循环中。

删除文件或文件夹

上面的链接有更多关于如何使用 Python 删除文件和文件夹的信息。查看最佳答案,该shutil.rmtree()函数看起来应该根据给定路径删除目录。

您可以在此处找到 shutil 文档

因此,如果您想继续打印所有这些变量,您的for循环应该只需要带有shutil.rmtree()函数的附加行:

for row in records:
    print (row)
    print("id = ", row["id"], )
    print("name = ", row["name"])
    print("state  = ", row["state"], "\n")
    shutil.rmtree(row["name"])

推荐阅读