Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查远程路径是文件还是目录?_Python_File_Directory_Paramiko - Fatal编程技术网

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'