Python 通过二进制或ASCII上传文本文件时是否将其保留为空?

Python 通过二进制或ASCII上传文本文件时是否将其保留为空?,python,ftp,binary,ascii,Python,Ftp,Binary,Ascii,因此,我一直在尝试制作一个插件,告诉另一端在FTP服务器上下载文本文件中的链接,我能够在服务器上接收当前版本并进行修改,但当我尝试重新上传时,文本文件显示为空白。我尝试过使用FTP.storline和FTP.storbinary,两者的结果相同。我将print函数放在回调函数中,以查看它是否正在发生。无论如何,任何关于为什么我无法发送包含所有附加数据的文件的帮助都是非常好的:D -克莱门特 代码: 回答: 抱歉这个愚蠢的问题,正如沃恩·卡托指出的,我不应该同时打开两个。我修正了在调用下一个文件之

因此,我一直在尝试制作一个插件,告诉另一端在FTP服务器上下载文本文件中的链接,我能够在服务器上接收当前版本并进行修改,但当我尝试重新上传时,文本文件显示为空白。我尝试过使用FTP.storline和FTP.storbinary,两者的结果相同。我将print函数放在回调函数中,以查看它是否正在发生。无论如何,任何关于为什么我无法发送包含所有附加数据的文件的帮助都是非常好的: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 = 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()

将同一文件打开两次是危险的,可能会导致意外行为。这样比较好:

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

您可能希望在检索文件后重新打开该文件,而不是同时打开文件两次。谢谢。在考虑了你的评论一分钟后,我意识到我不应该同时打开两个。我切换到了,这样“opened_llist.close()”就在编辑之后,然后我声明了第二个打开(RB)。您可能希望在检索文件后重新打开该文件,而不是同时打开文件两次。谢谢。在考虑了你的评论一分钟后,我意识到我不应该同时打开两个。我切换到了“opened_llist.close()”,编辑完成后,我宣布第二个开始(RB)。下面是关于回答自己问题的礼仪链接:下面是关于回答自己问题的礼仪链接: