使用ftplib遍历ftp中的文件在第二个循环中返回“没有这样的文件或目录”

时间:2019-02-19 19:38:17

标签: python ftp ftplib

我试图遍历ftp上的文件,然后存储它们。但是,在第二次迭代中,我收到错误:

FileNotFoundError: [Errno 2] No such file or directory:

这是我的代码:

# TODO: auth
from ftplib import FTP

def extract(environment):

    ftp = FTP(auth["host"])

    # Monitor and extract
    with ftp.login(user=auth['username'], passwd=auth['password']) as ftp:

        folders = []
        try:
            folders = ftp.nlst()
        except:
            print('Probably no folders in this directory')

        for f in folders:

            # Go into subfolder per subfund
            path = "".join(['/',f])
            ftp.cwd(path)

            # List files
            files = []
            try:
                files = ftp.nlst()
            except:
                print('Probably no files in this directory')

            for filename in files:
                if ".csv" in filename:

                    with open(filename, 'r+') as source_file:

                        print('opened, this works for the 1st only')
                        store_to_gcs(source_file, filename)


def store_to_gcs(source_file, filename)
    # TODO: bucket = storage.bucket(app=app)
    # After it I store it to GCS, does it have anything to do with it?

    storage_ref = "test/" + filename
    blob = bucket.blob(storage_ref)
    blob.upload_from_file(source_file)

with open(filename, 'r+') as source_file仅适用于文件中的第一个文件,不适用于第二个文件。

我可以像确认ftp.pwd()一样确认自己在正确的目录中。

1 个答案:

答案 0 :(得分:1)

let selectedUsers = users.filter{ $0.isSelected } 打开一个本地文件。虽然我相信您想打开一个远程文件。

您可能拥有open(filename, 'r+')的本地副本,但没有ffpos1_708524_57474156_18022019_036521_1.csv的本地副本。这就可以解释为什么fflia1_708470_57474842_18022019_036521_1.csv似乎在第一次迭代中成功了。


ftplib中没有类似open的函数。


有两种解决方案: