python - 使用 ftplib 循环 ftp 中的文件在第二个循环中返回 "No such file or directory"

标签 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 仅适用于 files 中的第一个文件,但不适用于第二个文件。

我可以确认我位于正确的目录中,就像我使用 ftp.pwd() 进行确认一样。

最佳答案

open(filename, 'r+') 打开本地文件。虽然我相信您想打开远程文件。

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

<小时/>

ftplib 中没有类似 open 的函数。

<小时/>

有两种解决方案:

关于python - 使用 ftplib 循环 ftp 中的文件在第二个循环中返回 "No such file or directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54773754/

相关文章:

python - 线性回归 - 输出不正确

python - 加载 Jupyter 服务器扩展时找不到模块

python - 无法理解 timeit 输出

python - 如何在Python 3中通过FTP从内存上传数据?

linux - 多次零星文件传输后 FTP 突然拒绝连接

python - 解压文件并从 ftp 下载

python - 使用python从ftp服务器下载文件但下载后文件未打开

python - 如何替换Python表达式中变量的值,但不计算表达式?

linux - 以最快的方式将文件发送到远程服务器

Python FTPLIB 错误 530 权限被拒绝