简体   繁体   English

Python-使用python ftplib模块下载所有文件夹,子文件夹和文件

[英]Python - download all folders, subfolders, and files with the python ftplib module

I have been working all day trying to figure out how to use the python ftplib module to download folders, subfolders, and files from an ftp server but I could only come up with this. 我一直在努力工作,以弄清楚如何使用python ftplib模块从ftp服务器下载文件夹,子文件夹和文件,但是我只能解决这个问题。

from ftplib import FTP
import sys, ftplib

sys.tracebacklimit = 0 # Does not display traceback errors
sys.stderr = "/dev/null" # Does not display Attribute errors

Host = "ftp.debian.org"
Port = 21
Username = ""
Password = ""

def MainClass():
    global ftp
    global con
    Host
    Port
    ftp = FTP()
    con = ftp.connect(Host, Port) # Connects to the host with the specified port

def grabfile():
    source = "/debian/"
    filename = "README.html"
    ftp.cwd(source)
    localfile = open(filename, 'wb')
    ftp.retrbinary('RETR ' + filename, localfile.write)
    ftp.quit()
    localfile.close()

try:
    MainClass()
except Exception:
    print "Not Connected"
    print "Check the address", Host + ":" + str(Port)
else:
    print "Connected"

if ftplib.error_perm and not Username == "" and Password == "":
    print "Please check your credentials\n", Username, "\n", Password

credentials = ftp.login(Username, Password)
grabfile()

This python script will download a README.html file from ftp.debian.org but, I would like to be able to download whole folders with files and subfolders in them and I cannot seem to figure that out. 这个python脚本将从ftp.debian.org下载README.html文件,但是,我希望能够下载其中包含文件和子文件夹的整个文件夹,但我似乎无法弄清楚。 I have searched around for different python scripts using this module but I cannot seem to find any that do what I want. 我已经使用此模块搜索了不同的python脚本,但是似乎找不到能满足我需要的任何脚本。

Any suggestions or help would be greatly appreciated. 任何建议或帮助将不胜感激。

Note: I would still like to use python for this job but it could be a different module such as ftputil or any other one out there. 注意:我仍然想使用python来完成这项工作,但是它可以是其他模块,例如ftputil或其他任何模块。

Thanks in advance, Alex 预先感谢Alex

The short solution: You could possibly just run: "wget -r ftp://username:password@ftp.debian.org/debian/ *" to get all the files under the debian directory. 简短的解决方案:您可能只需运行:“ wget -r ftp:// username:password@ftp.ftp.debian.org/debian/ *”即可获取debian目录下的所有文件。 Then you can process the files in python. 然后,您可以在python中处理文件。

The long solution: You can go over every directory listing by using ftplib, getting a directory listing parsing it and then getting every file and recursing into directories. 长期解决方案:您可以使用ftplib遍历每个目录列表,获取一个目录列表以对其进行解析,然后获取每个文件并递归到目录中。 If you search the web you'd find previous posts on stackoverlow which solve this issue 如果您在网上搜索,则会在stackoverlow上找到以前的帖子,这些帖子可以解决此问题

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

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