Thursday, September 22, 2016

Simple open_sftp() context manager for sftp read and writing of files

I had to do some reading/writing of files from an SFTP source/destination and ended up putting together a simple context manager for being able to do this so that it follows the same general interface as open() for local files. Usage is as simple as
from open_sftp import open_sftp

path = "sftp://user:p@ssw0rd@test.com/path/to/file.txt"

# Read a file
with open_sftp(path) as f:
    s = f.read() 
print s

# Write to a file
with open_sftp(path, mode='w') as f:
    f.write("Some content.") 
It's as simple as that. The full code can be found as a gist on GitHub. Note: This assumes that the directory already exists, but one could modify this trivially to create the path automatically by adding the details from this StackOverflow thread.

2 comments:

  1. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... Research help

    ReplyDelete
  2. You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. essay writing services uk

    ReplyDelete