-2

Let's say I have the following .txt file:

"StringA1","StringA2","StringA3"
"StringB1","StringB2","StringB3"
"StringC1","StringC2","StringC3"

And I want a nested list in the format:

nestedList = [["StringA1","StringA2","StringA3"],["StringB1","StringB2","StringB2"],["StringC1","StringC2","StringC3"]]

so I can access StringB2 for example like this:

nestedList[1][1]

What would be the best approach? I do not have a tremendous amount of data, maybe 100 lines at max, so I don't need a database or something

Luisss
  • 3
  • 2
  • 1
    Is there something with your current approach that doesn't satisfy you? Please clarify your exact problem. – Thierry Lathuille Nov 21 '21 at 19:05
  • My current approach was to enter my data into the array manually, but as I kept developing my program I wanted to externalize this data for the sake of being easier editable – Luisss Nov 21 '21 at 19:10
  • look at [import csv to list](https://stackoverflow.com/questions/24662571/python-import-csv-to-list) – Demi-Lune Nov 21 '21 at 21:50

2 Answers2

1

You can this sample code:

with open('file.txt') as f:
  nestedList = [line.split(',') for line in f.readlines()]

print(nestedList[1][1])
ahangaran
  • 69
  • 4
-1
file = open('a.txt').read()
file
l=[]
res = file.split('\n')
for i in range(len(res)):
    l.append(res[i].split(','))
print(l[1][1])

Assuming your file name as a.txt is having data in same format as you specified in question, i.e newline seperated so that we can add nested list, and data inside is ,(comma) seperated. Above code will give you the right output.

Jay Yadav
  • 236
  • 1
  • 2
  • 10