The Python Oracle

Downloading file with pysftp

This video explains
Downloading file with pysftp

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Question
00:55 Accepted answer (Score 37)
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/4463...

Accepted answer links:
[Connection.get]: https://pysftp.readthedocs.io/en/latest/...
[Connection.getfo]: https://pysftp.readthedocs.io/en/latest/...
[Read a file from server with SSH using Python]: https://stackoverflow.com/q/1596963/8508...
[Verify host key with pysftp]: https://stackoverflow.com/q/38939454/850...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sftp #pysftp

#avk47



ACCEPTED ANSWER

Score 39


Connection.get does not return anything. It downloads the remote file to a local path specified by the localpath argument. If you do not specify the argument, it downloads the file to the current working directory.

So if you want to download to a specific local directory instead, you want this:

sftp.get('directory/file.csv', '/local/path/file.csv')

If you really want to read the file to a variable (what I understand that you actually do not want), you need to use Connection.getfo, like:

flo = BytesIO()
sftp.getfo(remotepath, flo)
flo.seek(0)

Alternatively, use Paramiko library directly (without the pysftp wrapper).
See Read a file from server with SSH using Python.


Obligatory warning: Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.