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)?

>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()

Leave a Reply