2

I am trying to make a simple server-client interaction with Python using json. But now I have a problem, my .json file does upload, but then on the server-side it is empty.

Can you help me?

import json
import urllib.request
import os
import time
import ftplib
import fileinput
from ftplib import FTP

url = urllib.request.urlopen("http://example.com/path/data.json").read()
rawjson = url.decode("utf-8")

number = input("Bank number: ")

result = json.loads(url)

name = result[number]["name"]
salary = result[number]["salary"]

strsalary = str(salary)

newsalary = input("New salary: ")

os.system("wget http://example.com/path/data.json")

newtext = rawjson.replace(strsalary, newsalary)

textfile = open("data.json", "w")
textfile.write(newtext)

#domain name or server ip:
ftp = FTP('example.com','usr','pswd')
ftp.cwd("/path")
file=open('data.json', 'rb')
ftp.storbinary('STOR data.json', file)

This is the client-side script and I wanted to create a client server interaction via json with a simple webserver not a Python server.

0

1 Answer 1

2

Your code that writes the text file does not close it. Consequently, the file is likely not completely flushed to the disk yet, at the moment you try to read it for uploading.

To properly close the file, the best practice is to use the with block:

with open("data.json", "w") as textfile:
    textfile.write(newtext)

Though if you are using the file only as a way to temporarily store the data/text, which you want to upload to FTP, you do not have to use a physical file at all.

Use an in-memory file-like object instead, for example StringIO (or BytesIO):

from io import StringIO
ftp.storbinary('STOR data.json', StringIO(newtext))

See also Can I upload an object in memory to FTP using Python?


It's also quite strange that you download the file using a completely different API than you use to upload it. You should use FTP.retrbinary. Also similarly to the upload, you do not need to store the contents to a local file at all. You can download the contents to memory. But that's beyond the scope of this question.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.