我正在编写一个使用FTPLib来获取文件的模块。我想找到一种方法将值(除了块)传递给回调。基本上,我的回调是
def handleDownload(block, fileToWrite):
fileToWrite.write(block)
我需要致电
ftp.retrbinary('RETR somefile', handleDownload)
让它传递一个文件句柄。有没有办法做到这一点?
答案 0 :(得分:6)
您可以使用lambda:
关闭fileToWrite
变量
fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))
答案 1 :(得分:0)
此代码对我有用。
class File:
cleared = False
def __init__(self, filepath):
self.filepath = filepath
def write(self,block):
if not File.cleared:
with open(f'{self.filepath}', 'wb') as f:
File.cleared = True
with open(f'{self.filepath}', 'ab') as f:
f.write(block)
else:
with open(f'{self.filepath}', 'ab') as f:
f.write(block)
ftp.retrbinary("RETR somefile", File(filepath).write)