FTP upload issue in Python

2019-04-17 12:42发布

问题:

I am trying to upload a file to a remote server using Python 2.7, but when I run the script, the file on the remote FTP server is always called test_0test_ on remote FTP server, rather than test_0_13.pic.jpg as I would expect. Any ideas?

from ftplib import FTP

hosts = [('1.2.3.4', 'admin', '12345')]
local_file = r'/Users/foo/Downloads/13.pic.jpg'
remote_file_base_name_prefix = 'test_'
counter = 0
remote_file_base_name_suffix='_13.pic.jpg'

for host, name, password in hosts:
    f = FTP(host, name, password)
    f.cwd('Input')

    print remote_file_base_name_prefix+str(counter)+remote_file_base_name_suffix

    with open(local_file, 'rb') as f_local:
        f.storbinary('STOR {}'.format(remote_file_base_name_prefix+str(counter)+remote_file_base_name_prefix), f_local)

    print "{} - done".format(host)
    f.quit()

thanks in advance, Lin

回答1:

Ah, you just had a typo in your code:

f.storbinary('STOR {}'.format(remote_file_base_name_prefix+str(counter)+remote_file_base_name_prefix), f_local)

should be

f.storbinary('STOR {}'.format(remote_file_base_name_prefix+str(counter)+remote_file_base_name_suffix), f_local)


标签: python ftp