-3

I'm new to Python. I'm trying to open a text file and turn it into an array

The text file looks like this (textile.txt)

1,2022-05-01,37.2,70,18,120,80,95
1,2022-11-01,37.0,72,17,122,80,94
1,2023-05-01,37.1,71,16,121,78,93
1,2023-11-01,37.3,73,18,119,82,96
1,2024-05-01,37.0,69,19,120,80,95
2,2022-06-01,37.6,75,20,130,85,96
2,2022-12-01,37.8,74,19,128,84,95
2,2023-06-01,37.5,72,18,126,83,94
2,2023-12-01,37.7,73,21,130,86,97
2,2024-06-01,37.5,71,20,127,82,94
3,2022-07-01,36.9,68,16,118,75,93
3,2023-01-01,37.0,69,17,119,76,94
3,2023-07-01,36.8,67,15,117,74,92
3,2024-01-01,37.1,70,17,120,77,95
3,2024-07-01,36.9,68,16,118,75,93

I need an array that looks like this.

my_output = []
{1: [['2022-06-01', 37.2, 72, 16, 120, 80, 97], ['2022-09-15', 37.5, 73, 18, 125, 82, 96]], 2: [['2022-06-10', 36.9, 69, 18, 123, 80, 96], ['2023-01-03', 37.1, 71, 19, 124, 81, 97]], 3: [['2022-08-05', 37.3, 74, 20, 126, 83, 95], ['2023-03-01', 37.4, 75, 18, 123, 79, 98]]}

The data types are int, data, float, int, int, int, int

This is what I've been trying

my_output = []
with open ("textile.txt") as f:
    for line in f:
            id = [item.strip() for item in line.split(',')]
            my_output = append(id)

print(my_output)

all I get returned is []

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • The code you've shown should error, since `append` is not defined. – Mous Mar 21 '23 at 01:54
  • 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) – gre_gor Mar 21 '23 at 02:24

3 Answers3

0

You can use a defaultdict to store all the values corresponding to each id.

from collections import defaultdict
res = defaultdict(list)
with open("textile.txt") as f:
    for line in f:
        i, date, f, *rest = line.rstrip('\n').split(',')
        res[int(i)].append([date, float(f), *map(int, rest)])
print(res)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0
res = dict()
with open("textile.txt") as f:
    for line in f:
        i, date, f, *rest = line.split(',')
        i = int(i)
        if i not in res:
            res.setdefault(i, list())
        # convert str to int
        rest = list(map(int, rest))
        res[i].append([date, float(f), *rest])
print(res)
-1

use 'my_output.append(id)' instead 'my_output = append(id)', append is a class function of 'list', cannot use directly

  • and which is not an error but not recommended, don't use 'id' as an local variable because it's an python pre-defined function, for 'returns a unique id for the specified object' – imouttatime Mar 21 '23 at 02:22