robert williams
robert williams

Reputation: 767

creating two separate lists read from a file in python

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]

Upvotes: 0

Views: 98

Answers (3)

Julien Spronck
Julien Spronck

Reputation: 15423

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(';')]

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

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(";")]

Upvotes: 1

Aaron
Aaron

Reputation: 11075

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

Upvotes: 0

Related Questions