所以我一直在尝试制作一个插件来告诉另一端下载 FTP 服务器上文本文件中的链接,并且我能够接收服务器上的当前版本并对其进行修改,但是当我尝试重新上传文本文件显示为空白。我尝试使用 FTP.storline 和 FTP.storbinary ,两者都给出了相同的结果。我已将打印函数放入回调中,以查看是否发生了任何事情。无论如何,任何关于为什么我无法发送带有所有附加数据的文件的帮助都将非常好:D!
-克莱门特
代码:
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.")
已回答:
抱歉这个愚蠢的问题,正如沃恩·卡托指出的那样,我不应该同时打开两个。我修复了我的代码,在调用下一个文件之前关闭第一个打开的文件。最终代码如下所示:
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.")
最佳答案
将同一个文件打开两次是很危险的,并且可能会导致意外的行为。像这样的东西更好:
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()
关于python - 通过二进制或 ASCII 上传文本文件都会将其留空吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9322109/