0

Can i please know how the data from a file can be split into two separate lists. For example, file contains data as 1,2,3,4;5,6,7

my code:

for num in open('filename','r'):
  list1 = num.strip(';').split()

Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]

2
  • list1 = num.split(';')[0].split(',') list2 = num.split(';')[1].split(',') Commented Oct 17, 2016 at 14:59
  • Does the file have more than one line? What should happen at the line break? Commented Oct 17, 2016 at 15:03

3 Answers 3

2

If you are certain that your file only contains 2 lists, you can use a list comprehension:

l1, l2 = [sub.split(',') for sub in data.split(';')]
# l1 = ['1', '2', '3', '4']
# l2 = ['5', '6', '7']

More generally,

lists = [sub.split(',') for sub in data.split(';')]
# lists[0] = ['1', '2', '3', '4']
# lists[1] = ['5', '6', '7']

If integers are needed, you can use a second list comprehension:

lists = [[int(item) for item in sub.split(',')] for sub in data.split(';')]
Sign up to request clarification or add additional context in comments.

Comments

1

To get the final list you need to split on "," as well (and probably map() the result to int()):

with open("filename") as f: 
     for line in f:
         list1, list2 = [x.split(",") for x in line.rstrip().split(";")]

Comments

0

Depending on the size of your file, you could simply read the whole file into a string at once and then first split by semicolon, then by comma:

with open('filename', 'r') as f:  #open file
    s = f.read()   #read entire contents into string
    lists = s.split(';')  #split separate lists by semicolon delimiters
    for l in lists:  #for each list
        l = [int(x) for x in l.split(',')]  #separate the string by commas and convert to integers

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.