问题描述
我需要获取某些位置(系统和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_A 和 LOCATION_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秒即可运行整个代码。我正在寻找一种方法来优化时间并获取文件大小详细信息。
解决方法
Connection.listdir_attr
已经为您提供了SFTPAttributes.st_size
中的文件大小。
无需为每个文件调用Connection.stat
来获取大小(再次)。
另请参阅: