Python Forum

Full Version: Print to Text file in Python 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I save the values a variable to a text file in Python 3? i.e. my_varialbe = 'This is the text content" write my_variable to my_variable.txt Thank you!
You can do
from pathlib import Path
Path('my_variable.txt').write_text(my_variable)
Is file already existing and have content? If existing and with content - do you want to write it to new line or at the end of existing line?

One way to write (append) to file:

>>> my_variable = 'This is the text content.'
>>> with open('my_variable.txt', 'a') as f:
...     f.write(my_variable)