python - 通过 FTP 逐行读取 CSV,而不将整个文件存储在内存/磁盘中

标签 python csv ftp ftplib csvreader

我卡住了管道 ftplib.FTP.retrlinescsv.reader ...

FTP.retrlines 重复调用其中包含一行的回调,而 csv.reader 需要一个迭代器,该迭代器每次返回一个字符串 __next__() 方法被调用。

我如何将这两件事结合在一起,这样我就可以读取和处理文件,而无需提前读取整个文件,例如将其存储在一个文件中。 io.TextIOWrapper

我的问题是 FTP.retrlines 在它消耗了整个文件之前不会返回...

最佳答案

我不确定是否没有更好的解决方案,但您可以使用可迭代的类队列对象将 FTP.retrlinescsv.reader 粘合在一起。由于这两个函数是同步的,因此您必须在不同的线程上并行运行它们。

像这样:

from queue import Queue
from ftplib import FTP
from threading import Thread
import csv
 
ftp = FTP(host)
ftp.login(username, password)

class LineQueue:
    _queue = Queue(10)

    def add(self, s):
        print(f"Queueing line {s}")
        self._queue.put(s)
        print(f"Queued line {s}")

    def done(self):
        print("Signaling Done")
        self._queue.put(False)
        print("Signaled Done")

    def __iter__(self):
        print("Reading lines")
        while True:
            print("Reading line")
            s = self._queue.get()
            if s == False:
                print("Read all lines")
                break

            print(f"Read line {s}")
            yield s

q = LineQueue()

def download():
    ftp.retrlines("RETR /path/data.csv", q.add)
    q.done()

thread = Thread(target=download)
thread.start()

print("Reading CSV")
for entry in csv.reader(q):
    print(entry)

print("Read CSV")

thread.join()

关于python - 通过 FTP 逐行读取 CSV,而不将整个文件存储在内存/磁盘中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66117070/

相关文章:

python ftplib Transfercmd() 二进制模式

python - 不同时间步长的数据形状和 LSTM 输入

python - 转置一维 NumPy 数组

python - 使用 multipart_encode 的问题(海报库)

sqlite - 在sqlite studio中批量添加列的方法?

c# - FTP ://prompts for app 的 Process.Start

python - 在 python 中显示 ftp 上传的进度条

python - 使用 SQL 索引时 SQLAlchemy 自定义排序算法

android - 异步任务返回空指针

python - 使用 Python 将 .csv 文件转换为 .dbf?