简体   繁体   English

使用 Python,如何将 FTP 服务器上的子目录中的多个文件下载到本地计算机上的所需目录中?

[英]Using Python, how to download multiple files from a subdirectory on FTP server into a desired directory on local machine?

Using python program, I was able to download multiple source files from a FTP server (using ftplib and os libraries) to my local machine.使用 python 程序,我能够从 FTP 服务器(使用ftplibos库)将多个源文件下载到我的本地计算机。

These source file resides at a particular directory inside the FTP server.这些源文件位于 FTP 服务器内的特定目录中。

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.仅当我在本地计算机中提供了与 FTP 目录路径相同的目录路径时,我才能下载源文件。

I am able to download the files into C:\data\abc\transfer which is same as remote directory /data/abc/transfer .我可以将文件下载到与远程目录/data/abc/transfer相同的C:\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\但我想将所有文件下载到我想要的目录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.您必须提供open function 的完整路径,而不仅仅是目录名称。

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.要组装完整的本地路径,请从ftp.nlst返回的远程路径中获取文件名,并将它们与目标本地目录路径组合。

Like this:像这样:

local_fn = os.path.join(local_path, os.path.basename(file))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM