I just ran into this question yesterday when I was trying to download text files. Not sure if this is what you did, but since you say it has ASCII garbage in it, I assume you opened it in a text editor because it was supposed to be text.
If so, the problem is that the file is a text file and you are trying to download it in binary mode.
Instead, you want to receive the file in ASCII transfer mode.
tempFile = open(os.path.join(localDirectory,f),'w') # Changed 'wb' to 'w' ftpSession.retrlines('RETR '+f,tempFile.write) # Changed retrbinary to retrlines
Unfortunately, this removes all newlines from the file. Ugh!
So, you need to add the extra newline characters again:
tempFile = open(os.path.join(localDirectory,f),'w') textLines = [] ftpSession.retrlines('RETR '+f,textLines.append) tempFile.write('\n'.join(textLines))
This should work, but it doesnβt look as good as it could. So a little cleaning work will bring us:
temporaryFile = open(os.path.join(localDirectory, currentFile), 'w') textLines = [] retrieveCommand = 'RETR ' ftpSession.retrlines(retrieveCommand + currentFile, textLines.append) temporaryFile.write('\n'.join(textLines))
source share