0

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?

3
  • 1
    that's a strange format. Why would you want that? Commented Jun 1, 2021 at 6:17
  • because I want to access each element of the list of list so I can do further operations on that, for example I can do something on listID[0][3], listID[1][3], listID[2][3]...on the third element of each list Commented Jun 1, 2021 at 6:19
  • 1
    I would suggest using something like pandas. Using a standard tabular data format will pay significant dividends Commented Jun 1, 2021 at 6:21

1 Answer 1

4

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']]]
Sign up to request clarification or add additional context in comments.

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.