Error writing to file, you can not concatenate str a bytes

0

I've done a simple tcp server in Python and what I want to do is save the client's messages in a text file.

What happens is that when I try it, it means that you can not concatenate bytes to string.

Would they know how to do it? This is the server code:

import socket
file=open("mensajes.txt","w+")

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5550))
s.listen(5)
while True:
    sc, addr = s.accept()
    while True:
        recibido = sc.recv(1024)
        file.write(recibido+"\n")

        print ("Recibido: ", recibido,"utf-8".decode("ascii"))
        nuestra_respuesta = input("Tu: ")
        sc.send(nuestra_respuesta.encode('utf-8'))

file.close()
print ("Adios")
sc.close()
s.close()

and this is the error:

  

Traceback (most recent call last):
  File "clientpyhton.py", line 11, in
  file.write (received + "\ n")
  TypeError: can not concat str to bytes

    
asked by oscar 02.02.2018 в 17:45
source

1 answer

1

First of all, at least with what you show, you have not implemented a method to exit the infinite cycle correctly and close both the socket and the file correctly. You can use the event Ctrl + C for example to close the server securely. You can watch Capture KeyboardInterrupt .

Regarding your error, you open your file in text mode ( "w+" ) but you try to write bytes in it. The error in particular is because when you make recibido + '\n' you are trying to concatenate bytes ( recibido ) with a string str and therefore with encoding "utf-8" ( '\n' ).

Either you decode the string you receive before passing it to write :

import socket
import signal
import sys


file = open("mensajes.txt", "w+")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5550))
s.listen(5)


def keyboard_interrupt(signal, frame):
    file.close()
    print ("Adios")
    sc.close()
    s.close()
    sys.exit(0)

signal.signal(signal.SIGINT, keyboard_interrupt)


while True:
    print("Servidor iniciado. Pulse 'Ctrl'+'c' para salir")
    sc, addr = s.accept()
    while True:
        recibido = sc.recv(1024).decode("utf-8")
        file.write(recibido + "\n")
        print("Recibido: ", recibido)
        nuestra_respuesta = input("Tu: ")
        sc.send(nuestra_respuesta.encode('utf-8'))

Or open the file in binary mode:

import socket
import signal
import sys


file = open("mensajes.txt", "wb+")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5550))
s.listen(5)


def keyboard_interrupt(signal, frame):
    file.close()
    print ("Adios")
    sc.close()
    s.close()
    sys.exit(0)

signal.signal(signal.SIGINT, keyboard_interrupt)


while True:
    print("Servidor iniciado. Pulse 'Ctrl'+'c' para salir")
    sc, addr = s.accept()
    while True:
        recibido = sc.recv(1024)
        file.write(recibido + b'\n')
        print("Recibido: ", recibido.decode("utf-8"))
        nuestra_respuesta = input("Tu: ")
        sc.send(nuestra_respuesta.encode('utf-8'))

The line print("Recibido: ", recibido,"utf-8".decode("ascii")) is not valid in Python 3. I do not know what you want with "utf-8".decode("ascii") but str (string "utf-8" in Python 3) does not have the method decode as is logical, another thing is that Python 2 will be used.

    
answered by 02.02.2018 в 19:09