Generate file with Python dynamic name

Asked

Viewed 533 times

0

I’m creating communication sockets for some server-based devices. I need these devices to record information in the same file at all times. The file name needs to be the first characters inside your message.

import socket
import _thread

HOST = '192.168.0.63'
PORT = 5000

def conectado(con, cliente,):
    print ('Conectado por', cliente)

    while True:
        msg = con.recv(1024)
        if not msg: break
        print (cliente, msg,)

        arquivo = open(conectado, 'a+')
        arquivo.write(str(msg))
        arquivo.write('\n')
        arquivo.close()


    print ('Finalizando conexao do cliente', cliente)
    con.close()
    _thread.exit()

tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

orig = (HOST, PORT)

tcp.bind(orig)
tcp.listen(1)

while True:
    con, cliente = tcp.accept()
    _thread.start_new_thread(conectado, tuple([con, cliente,]))

tcp.close()

The device would send ASCII, starting with 8 numbers, which represent your ID. When trying to execute the code returns me the following error:

Unhandled exception in thread started by <function conectado at 0x7fd4ed513e18>
Traceback (most recent call last):
  File "/home/ubuntu/PycharmProjects/projeto1/projeto1.py", line 15, in conectado
    arquivo = open(conectado, 'a+')
TypeError: expected str, bytes or os.PathLike object, not function
  • TypeError: expected str, bytes or os.PathLike object, ie, was expected string, bytes or Pathlike object in the function open. You pass conectado for the open function, only conectado not string, but the function being executed.

  • How do I make pro script to define what will be the device name? According to the message it will receive

  • arquivo = open(conectado, 'a+'), here you try to open the file conectado, but this object is a function.

1 answer

-1


The correct use is:

arquivo = open("log_" + str(msg) + ".txt",'a+')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.