使用 Python ftplib 上传文件时出现“'NoneType' 对象没有属性 'sendall'”

"'NoneType' object has no attribute 'sendall'" when uploading file with Python ftplib

我制作了一个 FTP 客户端来将文件传输到 FTP 服务器,但是无论我如何更改 storbinary 函数

from ftplib import FTP
import os
from pathlib import Path

ftp = FTP()
ftp.connect('127.0.0.1', 2121)
ftp.login('user', '12345')
ftp.pwd()
ftp.retrlines('LIST')
ftp.quit()

def uploadfile():
    filename = 'C:\Users\RE\Desktop\Software dev\Ftp client and server\test.txt'
    localfile = open(filename, 'rb')
    ftp.storbinary('STOR %s' %os.path.basename(filename), localfile, 1024)
    localfile.close()

uploadfile()
ftp.retrlines('LIST')
fetchfile()
ftp.quit()

这是我的错误日志

Traceback (most recent call last):
  File "C:\Users\RE\Desktop\Software dev\Ftp client and server\ftp-client.py", line 24, in <module>
    uploadfile()
  File "C:\Users\RE\Desktop\Software dev\Ftp client and server\ftp-client.py", line 21, in uploadfile
    ftp.storbinary('STOR %s' %os.path.basename(filename), localfile, 1024)
  File "C:\Users\RE\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 503, in storbinary
    self.voidcmd('TYPE I')
  File "C:\Users\RE\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 277, in voidcmd
    self.putcmd(cmd)
  File "C:\Users\RE\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 199, in putcmd
    self.putline(line)
  File "C:\Users\RE\AppData\Local\Programs\Python\Python37\lib\ftplib.py", line 194, in putline
    self.sock.sendall(line.encode(self.encoding))
AttributeError: 'NoneType' object has no attribute 'sendall'

您正在有效地执行此操作:

ftp.quit()
uploadfile()

所以我相信很清楚,上传失败的原因。您在上传前关闭会话。