Home > Back-end >  Python nested list from file
Python nested list from file

Time:11-22

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

CodePudding user response:

You can this sample code:

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

print(nestedList[1][1])

CodePudding user response:

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.

  • Related