Paolo Lorenzini
Paolo Lorenzini

Reputation: 725

parse file to list of list in python

I have a tab separated txt file (file.txt) which looks like this:

Barcode1 ID644 79
Barcode2 ID232 80
Barcode3 ID008 09

I would like to convert it to list of list:

Expected output:

[[Barcode1], [ID644], [79]]
[[Barcode2], [ID232], [80]]
[[Barcode3], [ID008], [09]]

I tried this:

table_file=open("/Users/file.txt","r")
listID=[]
for line in table_file:
    line = line.strip('').split('\t')
    listID.append(line)

However I got something like this for the first line:

['Barcode1', 'ID644', '79\n'] ....

Any advice?

Upvotes: 0

Views: 49

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

You can use list comprehension on the line:

table_file = open("your_file.txt", "r")
listID = []
for line in table_file:
    line = line.split("\t")
    listID.append([[w.strip()] for w in line])

print(listID)

Prints:

[[['Barcode1'], ['ID644'], ['79']], 
 [['Barcode2'], ['ID232'], ['80']], 
 [['Barcode3'], ['ID008'], ['09']]]

Upvotes: 4

Related Questions