Reputation: 11
I'm trying to write a FTP upload program for text files. However I'm getting this error:
builtins.TypeError: a bytes-like object is required, not 'str'.
I am using Python 3.6.
Here is my code:
def _upload_to_ftp(self, ftp_handle, name):
# upload a single file to ftp directory
with open(name,'r') as f:
print("uploading"+name)
filename = os.path.basename(name)
ftp_handle.storlines('STOR %s' %filename, f)
I could not figure out why.
Upvotes: 1
Views: 2034
Reputation: 149075
Unfortunately, what FTP calls text is still bytes for Python 3. Python 3 strings use Unicode characters that need to be encoded to bytes in order to be written to files and FTP deals with files. But here it is even simpler: you have just to open the local file in binary mode to have it deliver bytes instead of strings:
def _upload_to_ftp(self, ftp_handle, name):
# upload a single file to ftp directory
with open(name,'rb') as f: # use binary mode for file
print("uploading"+name)
filename = os.path.basename(name)
ftp_handle.storlines('STOR %s' %filename, f)
Upvotes: 4