Pregunta

Mi script python2 archivos archivos muy bien utilizando este método, pero python3 se presentan problemas y estoy atascado en cuanto a dónde ir después (googlear no ha ayudado).

from ftplib import FTP
ftp = FTP(ftp_host, ftp_user, ftp_pass)
ftp.storbinary('STOR myfile.txt', open('myfile.txt'))

El error que consigo es

Traceback (most recent call last):
  File "/Library/WebServer/CGI-Executables/rob3/functions/cli_f.py", line 12, in upload
    ftp.storlines('STOR myfile.txt', open('myfile.txt'))
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 454, in storbinary
    conn.sendall(buf)
TypeError: must be bytes or buffer, not str

He intentado alterar el código a

from ftplib import FTP
ftp = FTP(ftp_host, ftp_user, ftp_pass)
ftp.storbinary('STOR myfile.txt'.encode('utf-8'), open('myfile.txt'))

Pero en cambio me dieron este

Traceback (most recent call last):
  File "/Library/WebServer/CGI-Executables/rob3/functions/cli_f.py", line 12, in upload
    ftp.storbinary('STOR myfile.txt'.encode('utf-8'), open('myfile.txt'))
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 450, in storbinary
    conn = self.transfercmd(cmd)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 358, in transfercmd
    return self.ntransfercmd(cmd, rest)[0]
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 329, in ntransfercmd
    resp = self.sendcmd(cmd)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 244, in sendcmd
    self.putcmd(cmd)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 179, in putcmd
    self.putline(line)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/ftplib.py", line 172, in putline
    line = line + CRLF
TypeError: can't concat bytes to str

me puede punto cualquiera en la dirección correcta

¿Fue útil?

Solución

El problema no es con el argumento de comando, pero con el objeto del archivo. Puesto que usted está almacenando binaria que necesita para abrir el archivo con la bandera 'rb':

>>> ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))
'226 File receive OK.'

Otros consejos

Añadir en el archivo de FTP.

Nota: No es SFTP - sólo FTP

import ftplib
ftp = ftplib.FTP('localhost')
ftp.login ('user','password')
fin = open ('foo.txt', 'r')
ftp.storbinary ('APPE foo2.txt', fin, 1)

Ref: Gracias a Noé

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top