0

What works

With the following code, I can write the content of TheList into a CSV on an SFTP.

import paramiko
import csv

# code part to make and open sftp connection

TheList = [['name', 'address'], [ 'peter', 'london']]

with sftp.open(SftpPath + "anewfile.csv", mode='w', bufsize=32768) as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    filewriter.writerows(TheList)

What doesn't work

With the following code, the Excel file is created on the SFTP, but it is empty. What is false?

import paramiko
import xlsxwriter

# code part to make and open sftp connection

TheList = [['name', 'address'], [ 'peter', 'london']]

with sftp.open(SftpPath + "anewfile.xlsx", mode='wb', bufsize=32768) as f:
    workbook = xlsxwriter.Workbook(f)
    worksheet = workbook.add_worksheet()
    for row_num, data in enumerate(TheList):
        worksheet.write_row(row_num, 0, data)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Gamsner
  • 117
  • 1
  • 9

1 Answers1

2

You need to close the Workbook. Either using the with statement:

with sftp.open(SftpPath + "anewfile.xlsx", mode='wb', bufsize=32768) as f, \
     xlsxwriter.Workbook(f) as workbook:
    worksheet = workbook.add_worksheet()
    for row_num, data in enumerate(TheList):
        worksheet.write_row(row_num, 0, data)

Or call Workbook.close explicitly:

workbook.close()
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • jad to remove the bufsize part. Now it works. YOu did help me. You may edit your answer, so I will accept for other users. – Gamsner Nov 17 '22 at 16:30
  • Not like `xlsxwriter.Workbook('test.xlsx')`. I've meant if you replace `sftp.open` with local `open`, keeping rest of the code. Removing `bufsize` seems like a hack, rather than a solution. Maybe try two nested `with` blocks (of the explicit `workbook.close()`) – Martin Prikryl Nov 17 '22 at 16:58