The close() method of FTP class in Python

The close() method, closes the connection at the client side of the FTP connection. It does not send a QUIT message to the FTP server. The Python example below interacts with the server through logging in and getting the contents of a directory before closing the connection at the client side.

Ftp Updated 16 Oct 2019 1 min read

Method Name

close

Method Signature

close()

Parameters

None

Return Value

None

Overview

  • The method close() closes the FTP connection from the client side.
  • It closes the socket and associated file handles associated with the connection.
  • The close() method does not make any interaction with the FTP server. Nor it takes care of waiting for any underlying transfers to be complete. It just closes the connection.This is in contrast to the implementation of quit(), which does the closing of the connection gracefully by sending the QUIT command to the FTP server.

Example

python
# Example Python program that uses the FTP.close() function

# to close an FTP connection from client side

from ftplib import FTP

hostName        = "agreatftpserver.com";

directoryName   = "/txt";

# Connect to the FTP host

ftp = FTP(host=hostName);

print(ftp.getwelcome());

# Login to the host

ftpReply = ftp.login();

print(ftpReply);

# Change to a desired directory

ftpReply = ftp.cwd(directoryName);

print(ftpReply);

# List the contents of the directory

ftpReply = ftp.dir();

print(ftpReply);

# Close the FTP connection from client side

ftpReply = ftp.close();

print(ftpReply);

Output

Output
220 (vsFTPd 3.0.3)

230 Login successful.

250 Directory successfully changed.

-rw-------    1 105      108      12628916 Oct 16 07:24 One.txt

-rw-------    1 105      108      12156928 Oct 16 07:28 Two.txt

-rw-------    1 105      108        638856 Oct 16 07:28 Three.txt

None

None