使用Python将特定文件上传到FTP目录

1 投票
1 回答
1620 浏览
提问于 2025-04-17 20:47

我需要把一些文件上传到FTP服务器上的不同文件夹里。这些文件的命名方式是这样的:

  • Broad_20140304.zip。
  • External_20140304.zip。
  • Report_20140304。

它们必须放到以下文件夹里:

  • Broad。
  • External。
  • Report。

我想要的是:比如文件名是External的,就把它放到External文件夹里。我有下面这段代码,但它把所有的zip文件都放到了“Broad”文件夹里。我只想把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"

1 个回答

0

这个函数里面有个固定的值给了 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"

撰写回答