繁体   English   中英

在python中浏览ftp目录

[英]Going through ftp directories in python

我正在尝试使用ftplib从使用Python 3的ftp服务器下载几个文件夹。

我有一个文件夹名称列表。 它们都位于文件夹“ root”中。 问题是我不知道如何浏览它们。 当我使用cwd我可以进入更深的目录,但是如何再次起床?

我正在尝试获得类似

list = ["folder1", "folder2", "folder3"]
for folder in list:
   ##navigate to folder
   ##do something

您可以使用FTP.pwd方法检索当前目录。 在更改目录之前,请记住该目录。

parent_dir = ftp_object.pwd()
list = ["folder1", "folder2", "folder3"]
for folder in list:
    ftp_object.cwd('{}/{}'.format(parent_dir, folder))
ftp_object.cwd(parent_dir) # go to parent directory

我对此处找到的代码进行了一些更改

您必须在运行代码之前创建目标文件夹。 另外,我使用的网站不需要用户名或密码。

请让我知道是否可行。 我想知道是否应该“把它放在我的后兜里”并将其保存到我的外部硬盘驱动器中。

    #!/usr/bin/python

import sys
import ftplib
import urllib.request
import os
import time
import errno

server = "ftp.analog.com"
#user = ""
#password = ""
source = "/pub/MicroConverter/ADuCM36x/"
destination0 = "C:/NewFolder/" # YOU HAVE TO UT THIS NEW FOLDER IN C: BEFORE RUNNING
interval = 0.05

ftp = ftplib.FTP(server)
ftp.login()#(user, password)

count = 0 #We need this variable to make the first folder correctly

def downloadFiles(path, destination):
    try:
        ftp.cwd(path)       
        os.chdir(destination)
        mkdir_p(destination[0:len(destination)-1] + path)
        print ("Created: " + destination[0:len(destination)-1] + path )
    except OSError:     
        pass
    except ftplib.error_perm:       
        print ( "Error: could not change to " + path )
        sys.exit("Ending Application")

    filelist=ftp.nlst()

    print(filelist)


    for file in filelist:
        time.sleep(interval)

        if "." in file :
            url = ("ftp://" + server + path + file)
            urllib.request.urlretrieve(url, destination + path + file)

        else:
            try:            
                ftp.cwd(path + file + "/")


                downloadFiles(path + file + "/", destination)
            except ftplib.error_perm:
                os.chdir(destination[0:len(destination)-1] + path)

                try:
                    ftp.retrbinary("RETR " + file, open(os.path.join(destination + path, file),"wb").write)
                    print ("Downloaded: " + file)
                except:
                    print ("Error: File could not be downloaded " + file)

    return


def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


downloadFiles(source, destination0)

#ftp.quit()

暂无
暂无

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

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