如何在Python中使用ftplib上传二进制文件?

时间:2010-05-26 09:44:34

标签: python ftplib

我的python2脚本很好地使用这种方法上传文件,但python3提出了问题,我对下一步去哪里感到困惑(谷歌搜索没有帮助)。

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

任何人都可以指出我正确的方向

2 个答案:

答案 0 :(得分:33)

问题不在于命令参数,而在于文件对象。由于您要存储二进制文件,因此需要使用'rb'标志打开文件:

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

答案 1 :(得分:2)

APPEND 以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