A
A
Arthur Samurai2020-04-29 21:44:42
Python
Arthur Samurai, 2020-04-29 21:44:42

How to write data to a file in python?

def on_press(key):
    l = '{0}'.format(key)

with Listener(
    on_press=on_press) as listener:
    listener.join()
f = open("log.txt", "w")
f.write(l)
f.close()


In this piece, the on_press function passes the pressed keys to the l variable. She never stops. Can you tell me how to write such data to the log file? What method or library to use? If you can give the code and briefly explain how it works) I tried it through pickle.dump and json, but to no avail.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2020-04-29
@zvepb

First, you need to format the code with a special tag.
Secondly, your variable l is local and not visible outside the function.
Thirdly, to write something to a file, it is better to use this construction:

with open("log.txt", "w") as f:
    f.write('any text')

In this case, the file is opened each time with overwriting, that is, clearing everything that was there before opening.
In order not to be deleted, you need to open it like this: Then the file will not be recreated on top of the old one and you can add data to it. Fourth, Python has a great logging module. Google an article about its use is elementary . And I won't have to write it all... Read the book. Well, why are you all climbing into programming while learning from rumors, legends and legends instead of reading articles and books, where everything is stated briefly and concisely. open('filename.log', 'a')

D
Dev12345, 2020-04-29
@Dev12345

Since you are logging to the file anyway, it would be more normal to use the logging library (special for logging, from python).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question