【问题标题】:Work with list variable in python 3 and delete folders based on it在 python 3 中使用列表变量并基于它删除文件夹
【发布时间】:2020-02-11 21:21:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: mysql python-3.x pymysql


    【解决方案1】:

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

    Delete a file or folder

    上面的链接有更多关于如何使用 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"])
    

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多