通过使用python连接到ftp从目录中拉出文件

时间:2018-06-21 08:17:48

标签: python ftplib

任务:我需要连接到客户端FTP,该服务器上有许多目录,每个目录中可能有也可能没有.csv文件。现在,我需要转到每个目录并打开所有目录中的文件,如果文件符合给定格式,则将其转储到服务器中。

目前我能够连接到FTP 我可以获取目录列表,但不能获取目录内的文件。

from ftplib import FTP
from sqlalchemy import create_engine
import os
import sys
import os.path


ftp=FTP('host')
ftp.login('user','pwd')

for files in ftp.dir():
    filenames=ftp.nlst(files)
    ftp.retrbinary("RETR " + a, file.write)
    file.close()


ftp.close()  #CLOSE THE FTP CONNECTION
print "FTP connection closed. Goodbye"

我知道这完全不符合要求。

1 个答案:

答案 0 :(得分:3)

看起来您正在寻找一种获取给定目录中文件列表的方法。这是我经常用于在unix系统(包括macOS)中解决此任务的功能。如果不是您要寻找的最终解决方案,那应该是一个很好的起点。

import glob, os
def list_of_files(path, extension, recursive=False):
    '''
    Return a list of filepaths for each file into path with the target extension.
    If recursive, it will loop over subfolders as well.
    '''
    if not recursive:
        for file_path in glob.iglob(path + '/*.' + extension):
            yield file_path
    else:
        for root, dirs, files in os.walk(path):
            for file_path in glob.iglob(root + '/*.' + extension):
                yield file_path

此外,您可以使用ftp.cwd('..')来更改目录,并使用ftp.retrlines('LIST')来获取该目录的文件列表。 检查docs以获得一些有用的代码段。