Reputation: 27
i'm trying to create a def for log file and this is my script:
import sys
import time
path= 'pc_path'
file = path + '\\' + 'test.txt'
files = open(file, 'w')
files.close()
def log(msg):
time = time.time()
filess = open(file, 'a')
filess.write(msg)
filess.close()
val = 10
val1 = 32
try:
operazione = val + val1
print('ok')
print(operazione)
msg = operazione
log(msg)
except:
sys.exit()
the script create a txt file but does not write a def() function into txt Thanks
Upvotes: 0
Views: 820
Reputation: 1091
You open a file, and then you close it. You don't write anything in it though, because the function write()
fails should anything but a variable of type str()
be passed to it! Here is an alternative to write()
with fewer restrictions:
with open('file_name.txt', 'w') as file:
print(variable_you_want_written, file=file, end='\n')
print()
function has fewer restrictions and is a better option here as it automatically formats the inputs it receives as a str()
, regardless of the initial type()
, and excluding functions, instances and generator objects, which would be displayed as, for instance, something like this: <function <lambda> at 0x1089b70d0>
.
Additionally, be aware that the visual format to which they are converted (and subsequently displayed or written in a file) may not necessarily be to your liking, so I suggest you do experiment with the results and see what works best in a particular situation.
Click here for Python 3 docs on print()
.
Upvotes: 1
Reputation: 690
Rename the variable time
to something like current_time
to avoid conflicts with the module time
.
You passed msg
, which is an integer, into the method write
. You should convert it to a string first: msg = str(operazione)
Upvotes: 0
Reputation: 1124968
You are trying to write an integer to a file; the file.write()
method only accepts strings.
Convert to a string first:
filess.write(str(msg))
You really should not use a blanket except
handler in your code; you really do't want to play Pokemon and catch them all. By doing so you are missing valuable error information. See Why is "except: pass" a bad programming practice?
Rather than roll your own, you could just use the logging
module.
Upvotes: 1