使用 Python,如何将多个文件从 FTP 服务器上的子目录下载到本地计算机上的所需目录中?
Using Python, how to download multiple files from a subdirectory on FTP server into a desired directory on local machine?
使用 python 程序,我能够从 FTP 服务器(使用 ftplib
和 os
库)将多个源文件下载到我的本地计算机。
这些源文件位于 FTP 服务器内的特定目录中。
仅当我在本地计算机中提供与 FTP 目录路径相同的目录路径时,我才能下载源文件。
我可以将文件下载到与远程目录 /data/abc/transfer
相同的 C:\data\abc\transfer
中。代码坚持要我提供相同的目录。
但我想将所有文件下载到我想要的目录中C:\data_download\
下面是代码:
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()
您必须提供 open
函数的完整路径,而不仅仅是目录名。
要assemble一个完整的本地路径,从ftp.nlst
返回的远程路径中获取一个文件名,并将它们与目标本地目录路径结合起来。
像这样:
local_fn = os.path.join(local_path, os.path.basename(file))
使用 python 程序,我能够从 FTP 服务器(使用 ftplib
和 os
库)将多个源文件下载到我的本地计算机。
这些源文件位于 FTP 服务器内的特定目录中。
仅当我在本地计算机中提供与 FTP 目录路径相同的目录路径时,我才能下载源文件。
我可以将文件下载到与远程目录 /data/abc/transfer
相同的 C:\data\abc\transfer
中。代码坚持要我提供相同的目录。
但我想将所有文件下载到我想要的目录中C:\data_download\
下面是代码:
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()
您必须提供 open
函数的完整路径,而不仅仅是目录名。
要assemble一个完整的本地路径,从ftp.nlst
返回的远程路径中获取一个文件名,并将它们与目标本地目录路径结合起来。
像这样:
local_fn = os.path.join(local_path, os.path.basename(file))