1

I have one file named Account.txt in SFTP server, and I'm trying to appending a line to this file. This is my effort:

from io import StringIO
from pysftp import Connection, CnOpts

cnopts = CnOpts()
cnopts.hostkeys = None
with Connection('ftpserver.com'
                ,username= 'username'
                ,password = 'password'
                ,cnopts=cnopts
                ) as sftp:
    with sftp.cd('MY_FOLDER'):
        f = sftp.open('Account.txt', 'ab')
        data='google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google'
        f.write(data+'\n')

When I run this above code, the file was overwritten, instead of appended. So, How can append new line but still keep the old lines in the file?

For example:

Account.txt file:

facebook|11111|Jack|Will||true|2018-09-21|2018-09-21|facebook
facebook|22222|Jack|Will||true|2018-09-21|2018-09-21|facebook

And now I want to add line "google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google" to the file. The result I'm expecting:

Account.txt file

facebook|11111|Jack|Will||true|2018-09-21|2018-09-21|facebook
facebook|22222|Jack|Will||true|2018-09-21|2018-09-21|facebook
google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google

Hope you guys can understand. Leave a comment if you don't. Thank you.

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
Han Van Pham
  • 392
  • 1
  • 5
  • 21

2 Answers2

1

Your code works for me with OpenSSH SFTP server.

Maybe it's a bug in Core FTP server.

You can instead try manually seeking file write pointer to the end of the file:

with sftp.open('Account.txt', 'r+b') as f:
    f.seek(0, os.SEEK_END)
    data='google|33333|Phu|Wood||true|2018-09-21|2018-09-21|google'
    f.write(data+'\n')
Basj
  • 36,818
  • 81
  • 313
  • 561
Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
-1

An addition to Martin's answer:

When using r+b, it will fail if the file does not exist yet. Use a+ instead if you want the file to be created if it does not exist, in a similar way to Difference between modes a, a+, w, w+, and r+ in built-in open function?.

Then no f.seek(0, os.SEEK_END) will be needed:

with sftp.open('test.txt', 'a+') as f:
    f.write('hello')
Basj
  • 36,818
  • 81
  • 313
  • 561