开发者

FTP files default download path(python)

开发者 https://www.devze.com 2023-03-22 18:01 出处:网络
when i download a file from ftp in python using retrbinary where are the files downloaded by default.Is there a way开发者_如何转开发 to change this default folder?

when i download a file from ftp in python using retrbinary where are the files downloaded by default.Is there a way开发者_如何转开发 to change this default folder? thanx in advance


The retrbinary function in the ftplib library takes a callback function that is called once for each block of data retrieved. You write this callback function yourself, and can therefore change the folder files are saved to.

Some example code:

#!/usr/bin/env python

import sys
from ftplib import FTP



ftphost, file_to_retrieve, output_path = sys.argv[1:4]

print "Retreiving %(file_to_retrieve)s from FTP host %(ftphost)s, saving to %(output_path)s" % locals()

ftp = FTP(ftphost)
ftp.login()

outfile = None
def data_callback(data):
    global outfile
    if outfile is None:
        outfile = open(output_path, 'w')

    outfile.write(data)

ftp.retrbinary("RETR %s" % file_to_retrieve, data_callback)

if outfile is not None:
    outfile.close()

To retreive ftp://ftp.sunet.se/pub/Linux/kernel.org/linux/docs/man-pages/man-pages-3.32.tar.gz and save it as /tmp/man-pages.tar.gz, run this code as follows:

$ python testftp.py ftp.sunet.se /pub/Linux/kernel.org/linux/docs/man-pages/man-pages-3.32.tar.gz /tmp/man-pages.tar.gz    
0

精彩评论

暂无评论...
验证码 换一张
取 消