pythonfile-uploadftpftp-clientftplib

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


I made an FTP client to transfer files to an FTP server, but it keeps showing me the same errors no matter how I change the storbinary function

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()

This is my error log

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'

Solution

  • You are effectively doing this:

    ftp.quit()
    uploadfile()
    

    So I believe it's quite clear, why the upload fails. You close the session before the upload.