Isura Nirmal
Isura Nirmal

Reputation: 787

Paramiko SFTP Client creates zero sized file after throwing IOError

Hi I am trying to copy a remote file in a server to a local location using Paramiko's SFTP client. Here below is the code.

    try:
        self.SFTP.get(remotepath, localpath, callback=None)
    except IOError as e:
        print "File Not Found  "+self.location

Remote location doesn't always contains the file requested so I want to print the Error message and end the process.

Unfortunately it prints the message(IOError message) but it also creates the local file with zero size.

Is this a bug or is there any other way to avoid this?

Upvotes: 1

Views: 2634

Answers (2)

RalphyZ
RalphyZ

Reputation: 863

I would use: sftp.stat(remotepath)

So, in your sample code:

try:
    if self.SFTP.stat(remotepath):
        self.SFTP.get(remotepath, localpath, callback=None)
except IOError as e:
    print "File Not Found  "+self.location

SFTP - Paramiko documentation

Upvotes: 2

Olivier
Olivier

Reputation: 156

It's expected.

Instead trying to get a file that you don't know if it exist, I suggest you either:

  • first try to find it using the Paramiko SFTP listdir command, or
  • try to get an SFTPFile object from it using Paramiko SFTP file command.
    • If it fails, the file doesn't exist.
    • If it succeeds, just close the SFTPFile object, and download the file with the get command.

Upvotes: 1

Related Questions