【问题标题】:Upload especific files to a ftp directory using python使用python将特定文件上传到ftp目录
【发布时间】:2014-03-05 00:37:28
【问题描述】:

我需要将一些文件上传到 ftp 服务器上的不同目录中。文件命名如下:

  • Broad_20140304.zip。
  • 外部_20140304.zip。
  • Report_20140304。

它们必须放在下一个目录中:

  • 广泛。
  • 外部。
  • 报告。

我想要类似的东西:对于像 External 这样的文件名,把它放到 External 目录中。 我有下一个代码,但这会将所有 zip 文件放入“广泛”目录中。我只希望将 broad.zip 文件放到这个目录中,而不是全部。

def upload_file():
    route = '/root/hb/zip'  
    files=os.listdir(route)
    targetList1 = [fileName for fileName in files if fnmatch.fnmatch(fileName,'*.zip')]
    print 'zip files on target list:' , targetList1
    try:
        s = ftplib.FTP(ftp_server, ftp_user, ftp_pass)
        s.cwd('One/Two/Broad')
        try:
            print "Uploading zip files"
            for record in targetList1:
                file_name= ruta +'/'+ record
                print 'uploading file: ' + record
                f = open(file_name, 'rb')
                s.storbinary('STOR ' + record, f)
                f.close()
            s.quit()
        except:
            print "file not here " + record
    except:
        print "unable to connect ftp server"

【问题讨论】:

    标签: python ftp


    【解决方案1】:

    该函数具有s.cwd 的硬编码值,因此它将所有文件放在一个目录中。您可以尝试以下方法从文件名中动态获取远程目录。

    示例:(未测试

    def upload_file():
        route = '/root/hb/zip'  
        files=os.listdir(route)
        targetList1 = [fileName for fileName in files if fnmatch.fnmatch(fileName,'*.zip')]
        print 'zip files on target list:' , targetList1
        try:
            s = ftplib.FTP(ftp_server, ftp_user, ftp_pass)
            #s.cwd('One/Two/Broad')  ##Commented Hard-Coded
            try:
                print "Uploading zip files"
                for record in targetList1:
                    file_name= ruta +'/'+ record
                    rdir = record.split('_')[0]  ##get the remote dir from filename
                    s.cwd('One/Two/' + rdir)     ##point cwd to the rdir in last step
                    print 'uploading file: ' + record
                    f = open(file_name, 'rb')
                    s.storbinary('STOR ' + record, f)
                    f.close()
                s.quit()
            except:
                print "file not here " + record
        except:
            print "unable to connect ftp server"
    

    【讨论】:

    • 感谢您的帮助,我试试看。