0

Hi hope everyone is okay.

I am trying to find the most simple method to take data from a text file and store it into diffrent variables. Below is the format of a text file:

TEXT FILE:

min:1,2,3,4,5,7,8,9

avg:1,2,3,4

max:1,2,3,4,5,1,2,3,44,55,32,12

I want to take each of these lines remove the part before the number starts (min,avg,max and the ':') and store all the number data in seperate variables in their appropriate names. NOTE: amount of numbers in each line may differ and shouldnt effect the code

desired in python:

min = [1,2,3,4,5,7,8,9]

avg = [1,2,3,4]

max = [1,2,3,4,5,1,2,3,44,55,32,12]

The code i have tried:

with open('input.txt', 'r') as input:
    input = input.read()
    input = input.strip().split(',')

After this part i am unsure which method would be best to achieve what I am trying to do. Any help is appriciated!

Slayer21
  • 1
  • 2
  • Do you have thoughts about what *input = input.read()* is going to do (notwithstanding that you've already shadowed the built-in *input()* function) – DarkKnight Feb 09 '23 at 18:08

3 Answers3

0

There's no reasonable way to generate variables (by name) dynamically. Better to use a dictionary. Something like this:

my_dict = {}

with open('input.txt') as data:
    for line in map(str.strip, data):
        try:
            key, vals = line.split(':')
            my_dict[key.rstrip()] = list(map(int, vals.split(',')))
        except ValueError:
            pass

print(my_dict)

Output:

{'min': [1, 2, 3, 4, 5, 7, 8, 9], 'avg': [1, 2, 3, 4], 'max': [1, 2, 3, 4, 5, 1, 2, 3, 44, 55, 32, 12]}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Hi thanks, how could we change this so that we can get the list by specifiing 'min' so that it would print all the data that follows min, same for avg and max – Slayer21 Feb 10 '23 at 08:43
  • @Slayer21 I refer you to the documentation: https://docs.python.org/3/tutorial/datastructures.html#dictionaries – DarkKnight Feb 10 '23 at 09:02
-1

Using exec for a string evaluation. Do that on trusted data to avoid injection attacks.

with open('input.txt', 'r') as fd:
   data = fd.read()


# list of lines
lines = data.split('\n')

# python code format
code_format = '\n'.join("{} = [{}]".format(*line.partition(':')[::2]) for line in lines if line)

# execute the string as python code
exec(code_format)

print(avg)
#[1, 2, 3, 4]

Notice that there is a further side effect in this code evaluation since some variable identifiers overload those of the built-in functions min, max. So, if after the execution of the code you try to call such build-in functions you will get TypeError: 'list' object is not callable.

One way to re-approach the problem would be by pickling the objects and use pickle.dumps to save an object to a file and pickle.loads to retrieve the object, see doc.

cards
  • 3,936
  • 1
  • 7
  • 25
-1

This is how you store it in a python dictionary:

txtdict = {}
with open('input.txt', 'r') as f:
  for line in f:
    if line.strip():
      name = line.split(':')[0]
      txtdict[name] = [int(i) for j in line.strip().split(':')[1:] for i in j.split(',')]

Output:

{'min': [1, 2, 3, 4, 5, 7, 8, 9],
 'avg': [1, 2, 3, 4],
 'max': [1, 2, 3, 4, 5, 1, 2, 3, 44, 55, 32, 12]}
Grg Alx
  • 83
  • 7
  • That's not really generating the desired output is it? It's also going to fail miserably if the input file contains empty lines as is apparently the case from the data shown in the question – DarkKnight Feb 09 '23 at 18:24
  • I edited my answer, it should work correctly now based on the information he provided – Grg Alx Feb 09 '23 at 20:00