我卡住了管道 ftplib.FTP.retrlines
至 csv.reader
...
FTP.retrlines
重复调用其中包含一行的回调,而 csv.reader
需要一个迭代器,该迭代器每次返回一个字符串 __next__()
方法被调用。
我如何将这两件事结合在一起,这样我就可以读取和处理文件,而无需提前读取整个文件,例如将其存储在一个文件中。 io.TextIOWrapper
?
我的问题是 FTP.retrlines
在它消耗了整个文件之前不会返回...
最佳答案
我不确定是否没有更好的解决方案,但您可以使用可迭代的类队列对象将 FTP.retrlines
和 csv.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/