Domanda

Il mio script python2 carica i file bene con questo metodo, ma python3 si presentano i problemi e mi sono bloccato su dove andare dopo (googling non ha aiutato).

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

L'errore che ottengo è

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

Ho provato a modificare il codice per

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

Ma invece ho ottenuto questo

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

Qualcuno può punto nella giusta direzione me

È stato utile?

Soluzione

Il problema non è con l'argomento comando, ma con l'oggetto del file. Dal momento che si stanno memorizzando binario è necessario aprire il file con la bandierina 'rb':

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

Altri suggerimenti

APPEND per file in FTP.

Nota: non è SFTP - FTP solo

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

Rif: Grazie a Noah

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top