gpt4 book ai didi

python - pysftp putfo 在 SFTP 服务器上创建一个空文件,但不传输来自 StringIO 的内容

转载 作者:行者123 更新时间:2023-12-01 07:06:16 25 4
gpt4 key购买 nike

我的代码首先将行写入 io.StringIO() 中的 CSV:

fileBuffer = io.StringIO()

# write header
header_writer = csv.DictWriter(fileBuffer, fieldnames=columnNames)
header_writer.writeheader()

# write lines
writer = csv.writer(fileBuffer, delimiter=',')

for line in data:
line_dec = line.decode('ISO-8859-1')
# print([line_dec])
writer.writerow([line_dec])

以下代码还打印所有预期的行:

$print(fileBuffer.getvalue())    # -> prints all expected rows

我还可以使用 pysftp 成功连接到 SFTP 服务器,甚至在使用 pysftp 时,代码也成功返回所有预期的行:

with pysftp.Connection(host, username=user, password=pw, cnopts=cnopts) as sftp: 
print('sucessfully connected to {} via Port 22'.format(host))
print(fileBuffer.getvalue()) # -> prints all expected rows
sftp.putfo(fileBuffer, file2BeSavedAs) # -> no rows put on FTP Server

实际问题来了:
不幸的是,代码只创建文件,而没有将数据和正文写入其中。另一方面,我的代码不会返回任何错误消息。

如何将 CSV 从 StringIO 放入 SFTP 服务器?

最佳答案

在尝试上传缓冲区之前,您必须将缓冲区的读取指针返回到开头:

fileBuffer.seek(0)
sftp.putfo(fileBuffer, file2BeSavedAs)
<小时/>

不过更好的方法是将 CSV 直接写入服务器,而不需要中间缓冲区。使用Connection.open获取代表 SFTP 服务器上文件的类文件对象:

with sftp.open(file2BeSavedAs, mode='w', bufsize=32768) as f:
writer = csv.writer(f, delimiter=',')
# ...

有关 bufsize 参数的用途,请参阅:
Writing to a file on SFTP server opened using Paramiko/pysftp "open" method is slow

<小时/>

对于类似的问题,带有进度显示,请参阅:
How to use Paramiko getfo to download file from SFTP server to memory to process it

<小时/>

虽然 pysftp 已经死了。你最好用Paramiko。请参阅pysftp vs. Paramiko 。对于 Paramiko,代码几乎是相同的。

关于python - pysftp putfo 在 SFTP 服务器上创建一个空文件,但不传输来自 StringIO 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com