-2

What type of data structure is this and how can I write it to a file?


    import datetime

    now = datetime.strftime(datetime.now(), "%Y-%m-%dT%H:%M:%S%Z")
    temp = 23
    humidity = 35

    data = '[{{ "timestamp": "{0}", "temperature": "{1:0.1f}", "humidity": "{2:0.1f}" }}]'.format(now, temp, humidity)

Thanks.

  • 1
    your code is *incomplete*. – de_classified Jun 10 '20 at 08:17
  • 2
    It is not a datastructure rather it's way to format strings in python, https://stackoverflow.com/a/517471/4985099 – sushanth Jun 10 '20 at 08:20
  • 1
    Like @Sushanth said, it's not a data structure. It's timestamp formated to string, then put together with other values. To put this data in file you can use this code snippet: `text_file = open("file.txt", "w")` `text_file.write(data)` `text_file.close()` Also to learn more about basic python, try [this interactive Python 3 course](https://www.codecademy.com/learn/learn-python-3). – richardev Jun 10 '20 at 08:51

1 Answers1

2

This is actually a string, as @Sushanth said:

from datetime import datetime
now = datetime.now()
temp=2.2341
humidity=2.123123
data = '[{{ "timestamp": "{0}", "temperature": "{1:0.1f}", "humidity": "{2:0.1f}" }}]'.format(now, temp, humidity)
print(data)
>>>[{ "timestamp": "2020-06-10 08:24:04.704800", "temperature": "2.2", "humidity": "2.1" }]

print(type(data))
>>><class 'str'>

Just it is created with format which allows us to insert a specified value(s) inside the string's placeholder. And, to write this string into a file, you can try this:

text_file = open("sample.txt", "w")
n = text_file.write(data)
text_file.close()

And if you want to create a new file with this variable data, you can checkout this link, and then open,write and close the file, as I showed you before.

MrNobody33
  • 6,413
  • 7
  • 19