mysql - 在 python 3 中使用列表变量并基于它删除文件夹
问题描述
抱歉,如果我命名错误,这是我第一次尝试在 python 中制作一些工作脚本。我用 列出了列表Dictionary Cursor
,但我现在需要将其作为变量并删除文件夹。例如。
如果我会在 ["name"] 中的选择中找到/data/system/domain.tld
并domain.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")
解决方案
假设上述语法工作正常,即生成row[name]
值是您希望删除的目录的路径的行,那么您只需将删除命令for
作为新行添加到循环中。
上面的链接有更多关于如何使用 Python 删除文件和文件夹的信息。查看最佳答案,该shutil.rmtree()
函数看起来应该根据给定路径删除目录。
因此,如果您想继续打印所有这些变量,您的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"])
推荐阅读
- objective-c - 如何在 MacOS 中保持沙盒模式获得批准的同时获取用户的 IP 地址?
- angular - 在包装器中显示 Angular Material mat-error
- c# - .NET Azure 函数 - 如何从流中返回 JSON 对象?
- c++ - Visual Studio 2015:外部“C”和“export”关键字
- python - 如何在预测中返回多个项目?
- excel - Excel 2016 Power Query 无法加载到电子表格
- scala - 可以将 udf 包装器添加到此数据帧操作
- ruby-on-rails - Spree API 身份验证扩展不起作用
- hive - 如何在 NiFi 中使用 UDF?
- tfs - 哪个是迭代 ID?