I'm working with transferring some Matlab code to Python. I'm relatively new to Python and am unsure of a Python equivalent of Matlab's textscan
method. Any help would be greatly appreciated.
If you're translating Matlab to Python, I'll assume you're already using NumPy.
In that case, you can use np.loadtxt
(if no values are missing) or np.genfromtxt
(if there are missing values: I'm not sure whether Matlab's textscan
handles that).
Give us a few more details if you need more help!
Example of conversion of MATLAB's textscan
to Python + NumPy's np.loadtxt
:
Let our data file results.csv
contain:
0.6236,sym2,1,5,10,10
0.6044,sym2,2,5,10,10
0.548,sym2,3,5,10,10
0.6238,sym2,4,5,10,10
0.6411,sym2,5,5,10,10
0.7105,sym2,6,5,10,10
0.6942,sym2,7,5,10,10
0.6625,sym2,8,5,10,10
0.6531,sym2,9,5,10,10
Matlab code:
fileID = fopen('results.csv');
d = textscan(fileID,'%f %s %d %d %d %d', 'delimiter',',');
fclose(fileID);
Python + NumPy code:
fd = open('results2.csv','r')
d = np.loadtxt(fd,
delimiter=',',
dtype={'names': ('col1', 'col2', 'col3', 'col4', 'col5', 'col6'),
'formats': ('float', 'S4', 'i4', 'i4', 'i4', 'i4')})
fd.close()
For more info on types, see Data type objects (dtype).
you have to look for Numpy and py2mat. If my understanding of textscan() is correct you could just use open()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With