So I have been trying to a make a plugin to tell the other end to download links in a text file on a FTP server and I am able to receive the current version on the server and modify it, but when I try to re-upload it the text file appears blank. I have tried using http://FTP.storline and http://FTP.storbinary with both giving me the same result. I’ve put the print function in the callback to see if anything it is happening which it isn’t. Anyways, any help as to why I am unable to send my file with all the data attached would be excellent :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:
Sorry for the silly question, as Vaughn Cato pointed out I should not have two open at the same time. I fixed my code be closing the first file opening before I call the next one. The final code looks like this:
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.")
Having the same file opened twice is dangerous and can lead to unexpected behaviour. Something like this is better: