Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I read 1 dimensional data from a text file into a 1D array? [Python]

I have a text file DATALOG1.TXT with values from 0 to 1023, pertaining to a signal. The file has one value per row, all values stored in a column. Here is an example of how the first values are stored in the file:

0
0
576
0
643
60
0
1012
0
455
69
0
1023
0
258

I have the following code, which outputs for the "magnitude" only values between 0 to 9, as if normalized. Here’s my code:

import matplotlib.pyplot as plt
import numpy as np


values = [] #array to be filled

#reading data from the file into the array
f = open('DATALOG1.TXT', 'r')
for line in f:
    values.append(line[0])

#creating another array of the same size to plot against
time = np.arange(0, len(values), 1)

plt.bar(time, values, color='g', label='File Data')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Magnitude', fontdsize=12)
plt.title('Magnitude changes', fontsize=20)
plt.show()

Why is the output between 0 and 9 as opposed to showing the values in the text file (between 0 and 1023)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By taking line[0] you just append the first character of each line to the list.

Since you already use numpy, you can use genfromtxt to load the data file.

import matplotlib.pyplot as plt
import numpy as np


values = [] #array to be filled

#reading data from the file into the array
values = np.genfromtxt('DATALOG1.TXT')


#creating another array of the same size to plot against
time = np.arange(0, len(values), 1)

plt.bar(time, values, color='g', label='File Data')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Magnitude', fontsize=12)
plt.title('Magnitude changes', fontsize=20)
plt.show()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading