Home > Net >  Python appending to file only after closing and re-opening code
Python appending to file only after closing and re-opening code

Time:10-07

I want to make a program, in which client gets to write something, then this text gets sent to the server and server saves this string to a txt file. I tried doing this, but I have a weird problem, where the text only gets saved to a txt file only after client closes and re opens the application. I tried googling but got nothing.

here is clients code:

import socket

c = socket.socket()

c.connect(('my ip here',5050))
info = input(" <<<")
c.send(bytes(info, 'utf-8'))

and here is the code of the server:

import socket

s = socket.socket()
print("Socket Created...")

s.bind((socket.gethostname(),5050))

s.listen(8)
print("Waiting for connections.")

while True:
  c, addr = s.accept()
  print("Connected with ", addr)

  info = c.recv(1024).decode()
  save = open("database.txt", "a")
  save.write(str(info))
  save.write("\n")
  save.close
  print(info)

  c.close

CodePudding user response:

You didn't call the close methods save.close nor c.close so the buffers didn't get flushed.

  • Related