I have a data set of float numbers in a file data.txt, which contains a variable number of columns per row. For example:
3.0 2.5
1.1 30.2 11.5
5.0 6.2
12.2 70.2 14.7 3.2 1.1
In order to read it, I can easily use a combination of fopen and fscanf in Matlab. The last one reads and converts the data into an array in column order, like this one:
array = [3.0 2.5 1.1 30.2 11.5 5.0 6.2 12.2 70.2 14.7 3.2 1.1]'
I want to translate my Matlab code into Python. But since there is no Python built-in function that replaces the Matlab's fscanf, I wrote the following Python code that reads and reshapes the data in the same way as described:
from numpy import *
data = []
with open('data.txt') as file:
for line in file:
cline = line.split()
data = data + cline
data = array(data)
This works, but some of my data sets can have up to 200,000 rows, and the Python code that I've shown is very slow for the reading of large data sets (about 10 minutes). On the other hand, Matlab's fscanf does the job in just a couple of seconds, or less. So, is there any faster (optimized) way than my code to do this in Python?
I would really appreciate any suggestion.