Extending Python's os.walk function on FTP server

后端 未结 4 1506
[愿得一人]
[愿得一人] 2021-02-15 15:01

How can I make os.walk traverse the directory tree of an FTP database (located on a remote server)? The way the code is structured now is (comments provided):

4条回答
  •  不要未来只要你来
    2021-02-15 15:36

    I needed a function like os.walk on FTP and there where not any so i thought it would be useful to write it , for future references you can find last version here

    by the way here is the code that would do that :

    def FTP_Walker(FTPpath,localpath):
        os.chdir(localpath)
        current_loc = os.getcwd()
        for item in ftp.nlst(FTPpath):
            if not is_file(item):
                yield from FTP_Walker(item,current_loc)
    
            elif is_file(item):
                yield(item)
                current_loc = localpath
            else:
                print('this is a item that i could not process')
        os.chdir(localpath)
        return
    
    
    def is_file(filename):
        current = ftp.pwd()
        try:
            ftp.cwd(filename)
        except Exception as e :
            ftp.cwd(current)
            return True
    
        ftp.cwd(current)
        return False
    

    how to use:

    first connect to your host :

    host_address = "my host address"
    user_name = "my username"
    password = "my password"
    
    
    ftp = FTP(host_address)
    ftp.login(user=user_name,passwd=password)
    

    now you can call the function like this:

    ftpwalk = FTP_Walker("FTP root path","path to local") # I'm not using path to local yet but in future versions I will improve it. so you can just path an '/' to it 
    

    and then to print and download files you can do somthing like this :

    for item in ftpwalk:
    ftp.retrbinary("RETR "+item, open(os.path.join(current_loc,item.split('/')[-1]),"wb").write) #it is downloading the file 
    print(item) # it will print the file address
    

    ( i will write more features for it soon so if you need some specific things or have any idea that can be useful for users i'll be happy to hear that )

提交回复
热议问题