Thank you much! I'm progressing.
This code downloads a file in my directory but, because I'm working with a microprocessor I'd like to download the file into the memories, make changes and upload it again into the ftp server.
How do I go by doing it?
Thank you.
This' what I tried:
This code downloads a file in my directory but, because I'm working with a microprocessor I'd like to download the file into the memories, make changes and upload it again into the ftp server.
How do I go by doing it?
Thank you.
from ftplib import FTP ftp_server = "192.168.1.10" url_username = "pi" url_pass = "mypi" filepath = "home/pi/iot" filename = "blynk.json" ftp = FTP(ftp_server) print(ftp.login(url_username, url_pass)) # 230 User pi logged in print(ftp.cwd(filepath)) # 250 CWD command successful print(ftp.retrlines('LIST')) # 226 Transfer complete with open(filename, "wb") as fp: # use FTP's RETR command to download the file ftp.retrbinary(f"RETR {filename}", fp.write) print(ftp.quit()) # 221 GoodbyeEDIT:
This' what I tried:
from ftplib import FTP from io import BytesIO import json ftp_server = "192.168.1.10" url_username = "pi" url_pass = "mypi" filepath = "home/pi/iot" filename = "blynk.json" data = [] def getFile(ftp, filename): try: ftp.retrbinary("RETR " + filename, open(filename, 'wb').write) except: print("Error") ftp = FTP(ftp_server) ftp.login(url_username, url_pass) ftp.cwd(filepath) data.append(getFile(ftp, filename)) print(data) # [None] ftp.quit()EDIT 2:
from ftplib import FTP from io import BytesIO import json def getFile(fp, fname): try: r = BytesIO() fp.retrbinary("RETR " + fname, r.write) data = r.getvalue().decode("utf-8") data = json.loads(data) # convert str to json return data except: print("ftp read error") def postFile(fp, fname, file): try: fp.storbinary("STOR" + fname, file) except: print("ftp post error") # open ftp connection ftp = FTP(ftp_server) # login ftp.login(url_username, url_pass) # 230 User pi logged in # change directory ftp.cwd(filepath) # 250 CWD command successful # list dir # print(ftp.retrlines('LIST')) # 226 Transfer complete # retrieve json data js_data = getFile(ftp, filename) print(js_data) # update json data js_data["relay3"] = "5555" print(js_data) # shows updated data # upload file postFile(ftp, filename, js_data) # close ftp connection ftp.quit() # 221 Goodbye
Error:ftp post error