write to file

Mark Lawrence breamoreboy at gmail.com
Sat May 5 07:51:12 EDT 2018


On 05/05/18 12:25, Sharan Basappa wrote:
> In my program, I have print statements for debugging.
> However, these are cluttering the display. So, I am trying to save
> these to a file but somehow I cant seem to get it correct.

Use the logging module https://docs.python.org/3/library/logging.html 
for debugging, it's far easier in the longer term.

> 
> For example, the following are the print statement in my program:
> print("target_names\n",target_names)
> 
> To print to a file, I have opened the file using - fh = open("ML_PY_2.log","w+")
> Beyond this, I see that fh.write has to be used but most of the examples I see only show how strings are saved.
> 
> Can I get input how to covert the above print statement to save into the file?

You'll need to do some string formatting.  Take your pick from :-

The old but still heavilly used C style 
https://docs.python.org/3/library/stdtypes.html#old-string-formatting

The new style 
https://docs.python.org/3/library/string.html#format-string-syntax

If you have Python 3.6 f-strings

> 
> Thanks in advance
> 

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list