使用python将特定文件上载到ftp目录

2024-09-30 22:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 广域网20140304.zip。在
  • 外部?20140304.zip。在
  • 报告_。在

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

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

我想要这样的东西:对于像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"

Tags: 文件in目录for报告ftpfileszip
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:22

该函数具有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"

相关问题 更多 >