簡體   English   中英

使用python將特定文件上傳到ftp目錄

[英]Upload especific files to a ftp directory using python

我需要將一些文件上傳到ftp服務器上的不同目錄中。 這些文件的命名如下:

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

必須將它們放置在以下目錄中:

  • 寬。
  • 外部。
  • 報告。

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

該函數具有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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM