How do I open a text file which contain several lists with floats only, read each list in this file and then append a new float to one of those lists?
Read text file with lists:
[1.0, 2.0, 3.1] #list 1
[5.1, 2.9, 7.1] #list 2
[6.6, 7.9, 3.1] #list 3
Open list 2 and append new float; 5.5
Results:
[1.0, 2.0, 3.1] #list 1
[5.1, 2.9, 7.1, 5.5] #list 2
[6.6, 7.9, 3.1] #list 3
I tried using json module and open/write function but i didnt figure it out.
Any good suggestions? :)
You can use json files for that. first, you need to create a json file that stores your lists:
import json
with open('data.json', 'w') as f:
json.dump(data, f)
Where data
contains your lists. data
can be a nested list of your float lists in the form
data = [[1, 2, 3], [3, 5, 2], [6, 7, 7]]
when you need to read the json file you can do this:
with open("data.json", "r") as f:
output = json.load(f)
Now output
has your lists and you can iterate over them and append your new number:
for nested_list in output:
nested_list.append(number)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.