2010-05-26 318 views
10

我的python2腳本很好地使用這種方法上傳文件,但python3呈現問題,我堅持下一步去哪裏(谷歌搜索沒有幫助)。如何在Python中使用ftplib上傳二進制文件?

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

我得到的錯誤是

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 

我試圖改變代碼

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

而是我得到這個

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 

可有人點我的正確的方向

+0

沒有什麼py3k獨佔這個問題。 – SilentGhost 2010-05-26 10:54:26

+1

這不是py3k的獨佔,而是通過相同的代碼突然拋出一個錯誤(並根據您的答案這是正確的做法),我認爲它可能是與字符串編碼相關的。 – Teifion 2010-05-26 12:49:00

回答

29

問題不在於命令參數,而在於文件對象。既然你存儲二進制你需要打開文件,'rb'標誌:

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

目前工作時,我會回家測試一下,希望所有人都會很開心,謝謝! – Teifion 2010-05-26 12:47:01

1

追加在FTP文件。

注:它不是SFTP - FTP只

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

編號:Thanks to Noah

相關問題