0

Well, i want to receive some bytes from a client to a server in python. So I send some strings from client: OLA, 135 and A.

The code lines of server is:

while True:
    # Receive the data one byte at a time
    data = connection.recv(1)
    file = open("test.txt", "w")
    file.write(data)
    file.close()
    sys.stdout.write(data)

I want to write these strings sended by client in a txt file. But after I received all strings in the server I open the txt file created and there are nothing. What is wrong?

nalzok
  • 14,965
  • 21
  • 72
  • 139
Leonardo
  • 3
  • 1
  • If file not found open in write mode, else open file in append mode. This looks like an infinite loop to me. When are you breaking out of the loop ? – Afaq Mar 15 '17 at 02:04
  • The code continues with: if data: # Send back in uppercase connection.sendall(data.upper()) else: print('no more data, closing connection.') break – Leonardo Mar 15 '17 at 02:08

1 Answers1

0

In python, open file with "w" removes previous file.

'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending;

So using "a" to keep existing data.

while True:
    # Receive the data one byte at a time
    data = connection.recv(1)
    file = open("test.txt", "a") # change 'w' to 'a'
    file.write(data)
    file.close()
    sys.stdout.write(data)

Reference : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

ikicha
  • 153
  • 7
  • Do you think that code: data = connection.recv(1) don't save the complete string received? – Leonardo Mar 15 '17 at 02:18
  • 1
    @Leonardo it basically rewrites the contents of your file since it is opened in 'w' mode! [This](http://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w) might help! – Keerthana Prabhakaran Mar 15 '17 at 03:03
  • @KeerthanaPrabhakaran It's working. Thank you very much. Can I request the created file from a web page? – Leonardo Mar 16 '17 at 00:20
  • @Leonardo do you wanna get html from url and save it as local file? – ikicha Mar 16 '17 at 00:29
  • @ikicha I want to request with a web page the .txt file created by the communication with client and server. My web page was another client. – Leonardo Mar 16 '17 at 01:30