首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ftplib遍历ftp中的文件时,在第二次循环中返回“没有这样的文件或目录”。

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

Stack Overflow用户
提问于 2019-02-20 03:38:17
回答 1查看 1.2K关注 0票数 2

我正在尝试遍历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仅适用于files中的第一个文件,而不适用于第二个文件。

我可以确认我在正确的目录中,就像我在ftp.pwd()中确认的那样。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-20 03:56:33

open(filename, 'r+')打开一个本地文件。而我相信你想打开一个远程文件。

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

在ftplib中没有open-like函数。

有两种解决方案:

  • 将文件下载到内存-即BytesIO类文件对象。

参见Retrieve data from gz file on FTP server without writing it locally

然后,您可以将BytesIO传递给blob.upload_from_file

这很容易实现,但如果文件太大,可能会有问题。

对于文件中的文件名:如果filename中的".csv“:flo = BytesIO() ftp.retrbinary('RETR‘+ filename,flo.write) flo.seek(0) store_to_gcs(flo,filename)

  • Implement )可以根据需要动态读取远程文件的自定义类文件对象。这比较复杂,但也是有可能的。

请参阅Get files names inside a zip file on FTP server without downloading whole archive.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54773754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档