As a python newbie still learning the language, I struggled for a couple of days trying to do a simple ASCII file transfer (STOR/PUT) using the ftp class in ftplib (running Python 3.3).
After using the storbinary() method and consistently getting a TypeError: "Type str doesn't support the buffer API", I discovered the discussion on this thread, which implies that there is a bug in the port of ftplib to Python 3:
http://bugs.python.org/issue6822
I then tried using storbinary() instead of storlines(), using a file object opened using the 'rb' switch and it seems to work perfectly. I'm working on a Windows system, and for testing/learning purposes I'm uploading to my own site which is on a Linux host. After uploading both .zip and .txt files and copying them back down to my workstation using FileZilla, both files are intact.
In my day-to-day work I need to upload gzipped and ASCII files to a mainframe, and am concerned that I may be leaving myself open to file transfer errors using this counter-intuitive work-around. I've screwed up so many manual FTP transfers when forgetting to switch to the appropriate transfer mode, that it feels creepy to be able to transfer both binary and ASCII files using exactly the same code!
Can anyone comment on how I'm implementing this library class?
Thanks.
fileName = 'F:\\Data_Folder\\Test_File.txt'
fileParts = os.path.split(fileName)
putFile = fileParts[1]
cmd = 'STOR {}'.format(putFile)
fileObject = open(fileName, 'rb')
ftp.storbinary(cmd, fileObject)
fileName = 'F:\\Data_Folder\\Test_File.zip'
fileParts = os.path.split(fileName)
putFile = fileParts[1]
cmd = 'STOR {}'.format(putFile)
fileObject = open(fileName, 'rb')
ftp.storbinary(cmd, fileObject)
6/28/2013 - Coming back here to kinda "close the loop" on this issue. While I can use open(fileName, 'rb') together with ftp.storbinary() successfully for both binary and ASCII text files, with both Windows and Linux hosts as the target, when I do so with the mainframe as the target, the text file is getting garbled, appearing as a binary file.
By adding a switch to my wrapper class to continue to open the file with the 'rb' argument, but using storlines() instead to do the transfer, the file arrives at the destination intact. I'm willing to bet that there are likely some configuration options on the mainframe side that could make this behavior vary from one host to another, but I'm hoping that mentioning this will alert anyone encountering this thread to the possibility that the apparently "safe" combination of open(fileName, 'rb') and storbinary() may not succeed with all FTP hosts, most notably mainframe systems. It may be only determined through trial-and-error, but there are cases in which the correct approach for transferring ASCII data will require open(fileName, 'rb') together with storlines().