2014-03-04 85 views
1

我需要將某些文件上載到ftp服務器上的不同目錄中。這些文件是這樣命名的:使用python將特定文件上傳到ftp目錄

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

它們必須被放置到下一個目錄:

  • 廣闊。
  • 外部。
  • 舉報。

我想要的東西像:對於像外部文件名將它放到外部目錄。 我有下一個代碼,但是這會將所有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" 

回答

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" 
+0

感謝您的幫助,我會盡力的。 – gegQ