【问题标题】:Python - move / upload specific files to FTPSPython - 将特定文件移动/上传到 FTPS
【发布时间】:2013-12-28 18:17:35
【问题描述】:

我正在尝试在 Windows 上使用 python 2.7 实现文件传输自动化。

所以我有一个 FTPS 服务器,我需要将一些文件从它移动到本地目录,并将一些文件从本地上传到 FTPS

FTPS的结构是这样的:

- ROOT FOLDER
    - AAA
        - abc_id1
            - in
            - out
        - abc_id2
            - in
            - out   
        - abc_id3
            - in
            - out
    - BBB
        - abc_id1
            - in
            - out
        - abc_id2
            - in
            - out   
        - abc_id3
            - in
            - out

我必须首先将所有匹配通配符 ABC_*.csv 的文件移动到本地目录,它们位于所有 /in 文件夹(例如 AAA\abc_id1\in)中

然后我必须从本地目录上传(复制)一些具有通配符的文件到相应的 abc_/in 文件夹(例如,名为 ABC_id3.csv 的文件必须转到 abc_id3 文件夹)

我已经开始编码了:

from ftplib import FTP_TLS

ftps = FTP_TLS('ip_address')
ftps.login("user", "pass")           # login before securing control channel
ftps.prot_p()          # switch to secure data connection
#ftps.retrlines('LIST') # list directory content securely

ftps.cwd("AAA")
ftps.retrlines('LIST')



ftps.quit()

但我不知道如何遍历多个文件夹来完成任务 请推荐一些代码

问候

【问题讨论】:

    标签: python for-loop wildcard directory ftps


    【解决方案1】:

    有两件事会有所帮助。使用os.walkgenerators 浏览目录。 您将需要遍历目录并检查每个文件。一旦确定它是您想要的文件,您就可以应用适当的 FTP 功能。

    这是我正在开发的一个应用程序中的一个示例。我还添加了排除功能。

    # Generator which runs through directories and returns files
    
    def scanDir (self, root, excludeDirs, excludeFiles, excludeExt, maxFileSize):
        global fileList
    
        print "Scanning directory " + root
        x = 0
        for root, dirnames, filenames in os.walk(root):
    
                for name in filenames:
                    #We want absolute path to these
                    absroot = os.path.abspath(root)
                    filename = os.path.join(absroot, name)
                    fileSize = os.path.getsize(filename) / 1024
                    x = x + 1
                    #print x
                    #@TODO compressed files call here (Extension)
                    if (os.path.isfile(filename) and os.path.getsize(filename) > 0): 
                        if fileSize > maxFileSize:
                            continue
                        else:
                            try:
                                #print root + name
                                os.path.getsize(filename)
                                data = open(root + "/" + name, 'rb').read()
                            except:
                                data = False
                                print "Could not read file :: %s/%s" % (root, file)
    
                            # TODO Create Exception here and filter file paths:
                            # regex for /home/*/mail
                            self.fileList.append({"filename":filename})
                            yield data, filename
    

    【讨论】:

      【解决方案2】:

      这是一个递归遍历 FTP 服务器并获取 zip 文件的示例,使用匿名登录。

      #!/usr/bin/env python
      
      from ftplib import FTP
      from time import sleep
      import os
      
      ftp = FTP('ftp2.census.gov')
      ftp.login()
      
      my_dirs = []  # global
      my_files = [] # global
      curdir = ''   # global
      
      def get_dirs(ln):
        global my_dirs
        global my_files
        cols = ln.split(' ')
        objname = cols[len(cols)-1] # file or directory name
        if ln.startswith('d'):
          my_dirs.append(objname)
        else:
          if objname.endswith('.zip'):
            my_files.append(os.path.join(curdir, objname)) # full path
      
      def check_dir(adir):
        global my_dirs
        global my_files # let it accrue, then fetch them all later
        global curdir
        my_dirs = []
        gotdirs = [] # local
        curdir = ftp.pwd()
        print("going to change to directory " + adir + " from " + curdir)
        ftp.cwd(adir)
        curdir = ftp.pwd()
        print("now in directory: " + curdir)
        ftp.retrlines('LIST', get_dirs)
        gotdirs = my_dirs
        print("found in " + adir + " directories:")
        print(gotdirs)
        print("Total files found so far: " + str(len(my_files)) + ".")
        sleep(1)
        for subdir in gotdirs:
          my_dirs = []
          check_dir(subdir) # recurse  
      
        ftp.cwd('..') # back up a directory when done here
      
      try:
        check_dir('/geo/tiger/GENZ2012') # root directory to start in
      except:
        print('oh dear.')
        ftp.quit()
      
      ftp.cwd('/.') # change to root directory for downloading
      for f in my_files:
        print('getting ' + f)
        file_name = f.replace('/', '_') # use path as filename prefix, with underscores
        ftp.retrbinary('RETR ' + f, open(file_name, 'wb').write)
        sleep(1)
      
      ftp.quit()
      print('all done!')
      

      【讨论】:

        猜你喜欢
        • 2019-01-31
        • 1970-01-01
        • 2019-12-06
        • 2018-10-23
        • 1970-01-01
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多