python 搜索ftp服务器中的文件和文件夹,获取详细信息,判断是否包含变量传入的某个目录或者某个文件

在Python中,你可以通过ftplib模块搜索FTP服务器中的文件和目录,并根据传入的变量判断是否存在指定的文件或目录。以下是修改后的代码示例:

 

python

import ftplib
from datetime import datetime

def search_ftp_files_and_folders(ftp_host, ftp_user, ftp_password, path='/', target_directory=None, target_file=None):
    # 创建并连接到FTP服务器
    with ftplib.FTP(ftp_host, ftp_user, ftp_password) as ftp:
        # 更改工作目录至指定路径
        ftp.cwd(path)

        # 使用mlsd()获取当前目录下所有项目(包括文件和目录)的详细信息
        entries = []
        try:
            response = ftp.mlsd()
            for name, details in response:
                entry = {'name': name}
                if isinstance(details, dict):
                    entry.update(details)
                    if 'modify' in entry:
                        entry['modify'] = datetime.strptime(entry['modify'], "%Y%m%d%H%M%S")
                entries.append(entry)
                
            # 检查是否存在传入的目标目录或文件
            def check_exists(target_name, target_type):
                matching_entries = [entry for entry in entries if entry['type'] == target_type and entry['name'] == target_name]
                return len(matching_entries) > 0

            contains_directory = check_exists(target_directory, 'dir') if target_directory else None
            contains_file = check_exists(target_file, 'file') if target_file else None

        except ftplib.error_perm as e:
            print(f"无法读取目录: {e}")

        return entries, contains_directory, contains_file

# 使用示例:
host = 'your.ftp.server.com'
username = 'your_username'
password = 'your_password'
target_dir = 'your_directory'
target_file = 'your_file'

entries, dir_exists, file_exists = search_ftp_files_and_folders(host, username, password, target_directory=target_dir, target_file=target_file)

print("包含指定目录:", dir_exists)
print("包含指定文件:", file_exists)

for item in entries:
    print(item)

在这个例子中,函数search_ftp_files_and_folders现在接受额外的参数target_directorytarget_file,并且在检查目标存在性时会考虑它们的类型('dir' 对应目录,'file' 对应文件)。在调用此函数时,请提供你想要查找的具体目录名和/或文件名。如果未提供这些值,则相应的contains_directorycontains_file将返回None。

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值