0

I want to read a tab separated file into a 2-D array where each line get stored in my 2-D array. I tried open and readline but nothing is working correct for me. Lets say my txt file is something like this :

1 2 3 4
2 3 4 5 
3 4 5 6 
...

so what I want is my 2-D array should store array[0]=[1,2,3,4], array[1]=[2,3,4,5] and so on.

Ajean
  • 5,528
  • 14
  • 46
  • 69
Rahul
  • 1

2 Answers2

1

From here

import csv
list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
Community
  • 1
  • 1
CasualDemon
  • 5,790
  • 2
  • 21
  • 39
0

If it is numerical data I suggest the following: use numpy like this

import numpy as np 

data = np.loadtxt('data.dat')

Optionally you can also specify a data type:

import numpy as np 

data = np.loadtxt('data.dat', dtype=np.float64)

If it is not numerical data, I would recommend csv like shown in the answer of CasualDemon:

import csv
list(csv.reader(open('data.dat', 'rb'), delimiter='\t'))