所以我一直试图制作一个插件告诉另一端在FTP服务器上的文本文件中下载链接,我能够在服务器上接收当前版本并修改它,但是当我尝试重新上传它,文本文件显示为空白。我尝试过使用FTP.storline和FTP.storbinary两个都给我相同的结果。我已经将print函数放在回调中,以查看它是否发生了什么事情。无论如何,任何关于为什么我无法发送附有所有数据的文件的帮助都会很棒:D!
-Clement
CODE:
def upload(link,ip,username,passwd):
present = False
connection = ftplib.FTP(ip)
connection.login(user=username,passwd=passwd)
items = connection.nlst()
for x in items:
if x == "list.txt":
present = True
break
if present == True:
username = os.getlogin()
print("Got login!")
locallist_dir = "/Users/" + username
locallist = locallist_dir + "/list.txt"
opened_llist_r = open(locallist, "rb")
opened_llist = open(locallist, "wt")
print("Opened file in", locallist)
connection.retrlines("RETR %s" % "list.txt", opened_llist.write)
print("Added lines from FTP")
opened_llist.write(link + " ")
print("Link:","'",link,"'","written!")
print(opened_llist," | ",opened_llist_r)
connection.storbinary("STOR %s" % "list.txt", opened_llist_r, 8192, print)
print("Re-uploaded!")
opened_llist.close()
opened_llist_r.close()
else:
print("Your current Connection does not have the list.txt file.")
connection.close()
print("Connection Closed.")
ANSWERED:
抱歉这个愚蠢的问题,因为Vaughn Cato指出我不应该同时打开两个。在我调用下一个文件之前,我修复了我的代码关闭第一个文件。最终代码如下所示:
def upload(link,ip,username,passwd):
present = False
connection = ftplib.FTP(ip)
connection.login(user=username,passwd=passwd)
items = connection.nlst()
for x in items:
if x == "list.txt":
present = True
break
if present == True:
username = os.getlogin()
print("Got login!")
locallist_dir = "/Users/" + username
locallist = locallist_dir + "/list.txt"
opened_llist = open(locallist, "wt")
print("Opened file in", locallist)
connection.retrlines("RETR %s" % "list.txt", opened_llist.write)
print("Added lines from FTP")
opened_llist.write(link + " ")
print("Link:","'",link,"'","written!")
print(opened_llist)
opened_llist.close()
opened_llist_r = open(locallist, "rb")
connection.storbinary("STOR %s" % "list.txt", opened_llist_r, 8192, print)
print("Re-uploaded!")
opened_llist_r.close()
else:
print("Your current Connection does not have the list.txt file.")
connection.close()
print("Connection Closed.")
答案 0 :(得分:1)
将同一个文件打开两次是危险的,可能会导致意外行为。这样的事情更好:
opened_llist = open(locallist, "wt")
connection.retrlines("RETR %s" % "list.txt", opened_llist.write)
opened_llist.write(link + " ")
opened_llist.close()
opened_llist_r = open(locallist, "rb")
connection.storbinary("STOR %s" % "list.txt", opened_llist_r, 8192, print)
opened_llist_r.close()