使用 python 3 中的列表变量并删除基于它的文件夹
Work with list variable in python 3 and delete folders based on it
抱歉,如果我命名错误,这是我第一次尝试 python 制作一些工作脚本。我用 Dictionary Cursor
制作了列表,但我现在需要使用 is 作为变量并删除文件夹。例如。
如果我在 /data/system/domain.tld
中找到并且 domain.tld
列在我的 ["name"] 中的 select 中,我想删除该目录。当我需要此功能时,我应该如何处理我的代码?
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
换行循环。
Delete a file or folder
上面的 link 有很多关于如何使用 Python 删除文件和文件夹的信息。查看最上面的答案,shutil.rmtree()
函数看起来应该根据给定路径删除目录。
You can find the shutil documentation here
因此,如果您想继续打印所有这些变量,您的 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"])
抱歉,如果我命名错误,这是我第一次尝试 python 制作一些工作脚本。我用 Dictionary Cursor
制作了列表,但我现在需要使用 is 作为变量并删除文件夹。例如。
如果我在 /data/system/domain.tld
中找到并且 domain.tld
列在我的 ["name"] 中的 select 中,我想删除该目录。当我需要此功能时,我应该如何处理我的代码?
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
换行循环。
Delete a file or folder
上面的 link 有很多关于如何使用 Python 删除文件和文件夹的信息。查看最上面的答案,shutil.rmtree()
函数看起来应该根据给定路径删除目录。
You can find the shutil documentation here
因此,如果您想继续打印所有这些变量,您的 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"])