I'd like to do a text file for the object in python.
For example, prepare the following text in advance, and
I'd like to substitute letters and matrices for the parts I want to change (variables 1-4) and output them as text.
Date—Variable 1
Weather—Variable 2
Temperature:
Variable 3 (matrix)
Humidity:
Variable 4 (matrix)
I know it's possible with for loops, but I'm looking for an easier way.
I thought YAML and JSON were similar, but I'm a beginner, so I don't know if I should use them.
I would appreciate it if you could let me know how to output files like this.
Thank you for your cooperation.
python text-file
How about using the str.format()
function?
#This is the template.
# In this case, the template is substituted as a string.
# You can also read it from a text file.
template='"Date: {date}
Weather: {weather}
Temperature:
{temp}
Humidity:
{humid}
'''
if__name__=="__main__":
date="Jan26,2018"
weather="Clear"
temp = 3
humid = [[10.0, 20.0, 30.0],
[40.0, 50.0, 60.0],
[70.0, 80.0, 90.0]]
# Use the str.format() function to substitute the template portion and output it as the print() function.
print(template.format(date=date, weather=weather, temp=temp, humid=humid))
Output
$python3 answer.py
Date: Jan 26, 2018
Weather: Clear
Temperature:
3
Humidity:
[[10.0, 20.0, 30.0], [40.0, 50.0, 60.0], [70.0, 80.0, 90.0]]
© 2025 OneMinuteCode. All rights reserved.