I have a class I use to track the progress of an ftp download (using ftplib
).
I use ftplib
with multiprocessing
to download several files at once.
This is my first attempt at using a class in Python and I am doubtful whether I am closing a file I opened inside the class. The code snippets I think relevent are given below:
class track_transfer:
def __init__(self, size, fname):
self.file_name=fname
self.size_in_bytes=size
self.downloaded=0
self.file=open(fname, 'wb')
def __del__(self):
try:
self.file.close()
self.file=None
except:
pass
def update(self):
self.downloaded=self.file.tell()
if self.downloaded==self.size_in_bytes:
self.file.close()
As you can see, I try to close the files at two places: one inside the finalizer another in a class method update()
.
What I wanted to know is will my file be closed correctly when I use this class?
Or is there a better method to follow?
UPDATE
I think I may need to provide more information here.
The class track_transfer has another method named progress(self, data) defined as follows:
def progress(self, data):
self.file.write(data)
self.update()
Instantiating the classAdded more information,
tracker=track_transfer(size=fsize, fname=fname)
and downloading the file,
ftp.retrbinary("RETR %s" %(fname),
callback=tracker.progress)
where ftp.retrbinary() is a method defined in the ftplib library to retrieve a file as binary from an ftp server. This will call the tracker objetc's progress method whenever a block of data is received. This means that the method progress() will be called several times when downloading a file.