0.续接上文
上传文件和目录,下载文件
1.上传代码如下所示
获取本地目录下的所有文件,带绝对路径的那种;
但是上传到远端,并没有创建目录,只是获取了本地所有文件的文件名。
上传文件
#你给我的两个地址,都必须是带文件名的;
远端默认英文路径,本地允许中文路径;远端文件名可以不同
def uploadFile(self,localPath,romatePath):
#time()返回1970到现在的浮点秒数
start = time.time()
#替换目录中的分隔符
localPath = localPath.replace('\\','/')
romatePath = romatePath.replace('\\','/')
#两个目录都是Unicode类型。
printLine("开始上传文件:%s"%localPath)
printLine(romatePath)
sftp = paramiko.SFTPClient.from_transport(self._transport)
# sftp.put(unicode(r''+localPath, 'utf-8'),r''+romatePath)
这种和下面都可以,目的都是允许中文目录。
sftp.put(localPath.decode('utf-8'),romatePath.decode('utf-8'))
sftp.close()
end = time.time()
printLine("传输成功,耗时%ds"%(end-start))
上传目录
def uploadDir(self,localPath,romatePath):
# 遍历目录,传输
start = time.time()
sftp = paramiko.SFTPClient.from_transport(self._transport)
try:
romatePath = romatePath.replace('\\','/')
sftp.mkdir(romatePath)
except:
printLine(romatePath+"是存在的!")
sftp.close()
files = self.get_all_dirs(localPath)
for filePath in files:
fileName = os.path.basename(filePath)
self.uploadFile(filePath,os.path.join(romatePath,fileName))
end = time.time()
printLine("本次目录%s传输成功,耗时%ds" % (localPath,end - start))
def get_all_dirs(self,local_dir):
local_dir = local_dir.decode('utf-8')
files = []
for parent,dirnames,filenames in os.walk(local_dir):
for fileName in filenames:
files.append(os.path.join(parent,fileName))
return files
2.下载代码如下所示
# 下载的两个参数都必须是文件,带文件名的那种!并且下载的文件名可以不同于远端
def downloadFile(self,romatePath,localPath):
start = time.time()
printLine("开始下载文件:%s"%romatePath)
sftp = paramiko.SFTPClient.from_transport(self._transport)
sftp.get(r''+romatePath,unicode(r''+localPath, 'utf-8'))
end = time.time()
printLine("传输成功,耗时%ds" % (end - start))