首页 > 解决方案 > 使用 pysftp 优化检索文件大小的性能

问题描述

我需要获取某些位置(在系统和 SFTP 内)的文件详细信息,并获取 SFTP 上某些位置的文件大小,这可以使用共享代码来实现。

def getFileDetails(location: str):
    filenames: list = []
    if location.find(":") != -1:
        for file in glob.glob(location):
            filenames.append(getFileNameFromFilePath(file))
    else:
        with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
            remote_files = [x.filename for x in sorted(sftp.listdir_attr(location), key=lambda f: f.st_mtime)]
            if location == LOCATION_SFTP_A:
              for filename in remote_files:
                filenames.append(filename)
                sftp_archive_d_size_mapping[filename] = sftp.stat(location + "/" + filename).st_size
            elif location == LOCATION_SFTP_B:
              for filename in remote_files:
                filenames.append(filename)
                sftp_archive_e_size_mapping[filename] = sftp.stat(location + "/" + filename).st_size      
            else:    
              for filename in remote_files:
                  filenames.append(filename)
            sftp.close()
    return filenames

LOCATION_SFTP_ALOCATION_SFTP_B中有超过10000个文件。对于每个文件,我需要获取文件大小。获得我正在使用的尺寸

sftp_archive_d_size_mapping[filename] = sftp.stat(location + "/" + filename).st_size
sftp_archive_e_size_mapping[filename] = sftp.stat(location + "/" + filename).st_size
# Time Taken : 5 min+
sftp_archive_d_size_mapping[filename] = 1 #sftp.stat(location + "/" + filename).st_size
sftp_archive_e_size_mapping[filename] = 1 #sftp.stat(location + "/" + filename).st_size
# Time Taken : 20-30 s

如果我注释sftp.stat(location + "/" + filename).st_size并分配静态值运行整个代码只需要 20-30 秒。我正在寻找一种如何优化时间并获取文件大小详细信息的方法。

标签: pythonpython-3.6sftppysftp

解决方案


Connection.listdir_attr已经为您提供了SFTPAttributes.st_size.

无需Connection.stat(再次)调用每个文件来获取大小。

也可以看看:


推荐阅读