Python 如何检查远程路径是文件还是目录?
我正在使用Python 如何检查远程路径是文件还是目录?,python,file,directory,paramiko,Python,File,Directory,Paramiko,我正在使用SFTPClient从远程服务器下载文件。但我不知道远程路径是文件还是目录。如果远程路径是一个目录,我需要递归地处理这个目录 这是我的代码: def downLoadFile(sftp, remotePath, localPath): for file in sftp.listdir(remotePath): if os.path.isfile(os.path.join(remotePath, file)): # file, just get try:
SFTPClient
从远程服务器下载文件。但我不知道远程路径是文件还是目录。如果远程路径是一个目录,我需要递归地处理这个目录
这是我的代码:
def downLoadFile(sftp, remotePath, localPath):
for file in sftp.listdir(remotePath):
if os.path.isfile(os.path.join(remotePath, file)): # file, just get
try:
sftp.get(file, os.path.join(localPath, file))
except:
pass
elif os.path.isdir(os.path.join(remotePath, file)): # dir, need to handle recursive
os.mkdir(os.path.join(localPath, file))
downLoadFile(sftp, os.path.join(remotePath, file), os.path.join(localPath, file))
if __name__ == '__main__':
paramiko.util.log_to_file('demo_sftp.log')
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
我发现问题在于:
函数os.path.isfile
或os.path.isdir
返回False
,因此我认为这些函数不能用于远程路径。os.path.isfile()
和os.path.isdir()
仅适用于本地文件名
我将使用sftp.listdir\u attr()
函数,加载完整的SFTPAttributes
对象,并使用stat
模块实用程序函数检查它们的st\u mode
属性:
import stat
def downLoadFile(sftp, remotePath, localPath):
for fileattr in sftp.listdir_attr(remotePath):
if stat.S_ISDIR(fileattr.st_mode):
sftp.get(fileattr.filename, os.path.join(localPath, fileattr.filename))
使用模块
要验证远程路径是文件还是目录,请遵循以下步骤: 1) 创建与远程服务器的连接
transport = paramiko.Transport((hostname,port))
transport.connect(username = user, password = pass)
sftp = paramiko.SFTPClient.from_transport(transport)
2) 假设您有目录“/root/testing/”,并且希望通过ur code.Import stat包进行检查
import stat
3) 使用下面的逻辑检查其文件或目录
fileattr = sftp.lstat('root/testing')
if stat.S_ISDIR(fileattr.st_mode):
print 'is Directory'
if stat.S_ISREG(fileattr.st_mode):
print 'is File'
如果有扩展名,请检查路径的扩展名。文件不一定有扩展名。此代码可能存在重复的问题吗?@thefourtheye我只想使用
SFTPClient
下载一个目录。
fileattr = sftp.lstat('root/testing')
if stat.S_ISDIR(fileattr.st_mode):
print 'is Directory'
if stat.S_ISREG(fileattr.st_mode):
print 'is File'