Using python program, I was able to download multiple source files from a FTP server (using ftplib
and os
libraries) to my local machine.
These source file resides at a particular directory inside the FTP server.
I was able to download the source files only if I have provided the same directory path in my local machine, as of FTP directory path.
I am able to download the files into C:\data\abc\transfer
which is same as remote directory /data/abc/transfer
. Code is insisting me to provide the same directory.
But I want to download all files into my desired directory C:\data_download\
Below is the code :
import ftplib
import os
from ftplib import FTP
Ftp_Server_host = 'xcfgn@wer.com'
Ftp_username ='qsdfg12'
Ftp_password = 'xxxxx'
Ftp_source_files_path = '/data/abc/transfer/'
ftp = FTP(Ftp_Server_host)
ftp.login(user=Ftp_username, passwd=Ftp_password)
local_path = 'C:\\data_download\\'
print("connected to remote server :" + Ftp_Server_host)
print()
ftp_clnt = ftp_ssh.open_sftp()
ftp_clnt.chdir(Ftp_source_files_path)
print("current directory of source file in remote server :" +ftp_clnt.getcwd())
print()
files_list = ftp.nlst(Ftp_source_files_path)
for file in files_list:
print("local_path :" + local_path)
local_fn = os.path.join(local_path)
print(local_fn)
print('Downloading files from remote server :' + file)
local_file = open (local_fn, "wb")
ftp.retrbinary("RETR " + file, local_file.write)
local_file.close()
print()
print("respective files got downloaded")
print()
ftp_clnt.close()
You have to provide a full path to open
function, not just a directory name.
To assemble a full local path, take a file name from the remote paths returned by ftp.nlst
and combine them with the target local directory path.
Like this:
local_fn = os.path.join(local_path, os.path.basename(file))