简体   繁体   中英

Python - download a file from a ftp server to a different local name

I have the following code:

ftp = ftplib.FTP(ftp_srv)
ftp.login(ftp_usr, ftp_pass)

for item in list:
    f = open(item.localName,"wb")
    ftp.retrbinary("RETR " + item.remoteName, f.write)
ftp.quit()
  • "localName" is the name of the file on the local machine, for example: one.txt
  • "remoteName" is the name of the file on the FTP server with full path, something like "/share/path/to/file.txt"

In perl this was very easy:

 $ftp->get($ftp_file, $local_file)

EDIT: The code above does not work. I would like to download the remoteName file to the local machine and on the local machine that file to be named localName. How do I do that? :D EDIT2: made it a list

Thank you

The main problems with your code are that:

  • item is never actually used in the for loop
  • localName or remoteName are not specified anywhere

This code works on my machine:

import ftplib

ftp_srv = 'ftp.example.com'
ftp_usr = 'user'
ftp_pass = 'password'

ftp = ftplib.FTP(ftp_srv)
ftp.login(ftp_usr, ftp_pass)

files = [('remote_file1', 'local_file1'), ('remote_file2', 'local_file2')]

for file_ in files:
    with open(file_[1], "wb") as f:
        ftp.retrbinary("RETR " + file_[0], f.write)
ftp.quit()

Each file_ is a tuple which contains the name of the file on the server, and the name you want it to have on your local machine, which are referred to using the square bracket notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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