Ameer Hamza
Ameer Hamza

Reputation: 85

Python: How to parse data from text file to 2 Dimensional list/array

I have data like this stored in a text file:

ABC,0x1: XYZ,0x2:

I want to parse this data into 2 dimensional array, currently i can parse data separated by ':' using following code,

text_file = open("string.txt", "r")
parsed_data = text_file.read().split(':')

My question is that how can i store this data into 2-D list such that parsed_data[0][0] will contain ABC, parsed_data[0][1] contain 0x1 and so on.

Upvotes: 1

Views: 593

Answers (2)

blhsing
blhsing

Reputation: 107134

You can use list comprehension like this:

parsed_data = [t.split(',') for t in text_file.read().split(':')]

Upvotes: 1

Sven Harris
Sven Harris

Reputation: 2939

You could try something like this:

with open("string.txt", "r") as text_file:
    parsed_data = [[x.split(",")[0], x.split(",")[1]] for x in text_file.read().split(':') if x != ""]

Upvotes: 0

Related Questions