python - pysmb递归删除文件夹子文件夹和文件

标签 python python-3.x

我有一个共享文件夹,根目录下有一个文件夹,里面有子文件夹和文件。

我找不到如何递归删除根目录下的文件夹及其子文件夹和文件。

请问有什么帮助吗

谢谢

最佳答案

这是 Michael 为 python 2.7 编写的函数:

from smb.SMBConnection import SMBConnection

dry_run = True  # Set to True to test if all files/folders can be "walked". Set to False to perform the deletion.
userID = 'myuser'
password = 'mypassword'
client_machine_name = 'testclient'   # Usually safe to use 'testclient'
server_name = 'MYSERVER'   # Must match the NetBIOS name of the remote server
server_ip = '192.168.1.10' # Must point to the correct IP address
domain_name = ''           # Safe to leave blank, or fill in the domain used for your remote server
shared_folder = 'smbtest'  # Set to the shared folder name

conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True, is_direct_tcp=True)
conn.connect(server_ip, 445)

def walk_path(path):
    print 'Walking path', path
    for p in conn.listPath(shared_folder, path):
        if p.filename!='.' and p.filename!='..':
            parentPath = path
            if not parentPath.endswith('/'):
                parentPath += '/'

            if p.isDirectory:
                walk_path(parentPath+p.filename)
                print 'Deleting folder (%s) in %s' % ( p.filename, path )
                if not dry_run:
                    conn.deleteDirectory('smbtest', parentPath+p.filename)
            else:
                print 'Deleting file (%s) in %s' % ( p.filename, path )
                if not dry_run:
                    conn.deleteFiles('smbtest', parentPath+p.filename)

# Start and delete everything at shared folder root
walk_path('/')

关于python - pysmb递归删除文件夹子文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871317/

相关文章:

python - 使用 BeautifulSoup 提取数据

python - 使用 Pandas GroupBy 和 value_counts 查找最常见的值

python - ffmpeg - 在图像顶部叠加视频

python - 使用 werkzeug 从文件中解析和保存多部分表单数据

python - 需要帮助创建具有重复键的字典

有/没有列表理解的python函数调用

python - 类型错误 : KMeans() got an unexpected keyword argument 'n_clusters'

python-3.x - 使用influxdb-python的Influxdb批量插入

Python:随脚本交付的自定义包及其导入方式

python - 如何以半小时为间隔划分 Pandas 日期时间列