0

Let's say I have a text file that contains data such as this:

data1:data2
data1:data2
data1:data2
data1:data2

I want to split this data into two separate arrays. One array containing the data from the left hand side of the colon, and the other containing the data from the right hand side.

What would be the most efficient way of going about it?

2 Answers 2

4

Easyest way is just to split each line on the colon and append to two seperate arrays

Example:

infile = open(listfile,'r')
filecontent = infile.readlines()
infile.close()
array1 = []
array2 = []
for line in filecontent:
    tmp = line.strip().split(':')
    array1.append(tmp[0])
    array2.append(tmp[1])
Sign up to request clarification or add additional context in comments.

Comments

1

A few list comprehensions can do this pretty handily.

with open(filename) as f:
    lists = [line.strip().split(':') for line in f.readlines()]
listOne = [line[0] for line in lists]
listTwo = [line[1] for line in lists]

Storing lists and then separating it saves having to read through the whole file twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.