通过 pysftp 附加到 SFTP 服务器上的现有文件

Append to existing file on SFTP server via pysftp

我在 SFTP 服务器中有一个名为 Account.txt 的文件,我正在尝试向该文件追加一行。这是我的努力:

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')

当我运行上面的代码时,文件被覆盖,而不是追加。那么,如何追加新行但仍保留文件中的旧行?

例如:

Account.txt 文件:

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"。 我期待的结果:

Account.txt 文件

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

希望大家能够理解。如果你不这样做,请发表评论。谢谢。

你的代码适用于我的 OpenSSH SFTP 服务器。

可能是 Core FTP 服务器中的错误。

您可以尝试手动寻找指向文件末尾的文件写入指针:

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')

马丁回答的补充:

使用r+b时,如果文件不存在,会失败。如果您希望在文件不存在时创建文件,请改用 a+,类似于 Difference between modes a, a+, w, w+, and r+ in built-in open function?.

那么就不需要f.seek(0, os.SEEK_END)了:

with sftp.open('test.txt', 'a+') as f:
    f.write('hello')