-1

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? :)

realr
  • 3,652
  • 6
  • 23
  • 34
  • What does the text file actually look like? Does a line have brackets and the comment #list number? How do you want to determine which list to append - just list 2? – DaveStSomeWhere May 04 '20 at 20:11
  • Sounds like a homework about how to manipulate CSV-like files. – Ramon Moraes May 04 '20 at 20:27
  • Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – Ramon Moraes May 04 '20 at 20:28

1 Answers1

0

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)
Gal
  • 504
  • 4
  • 11