Archisman Panigrahi
Archisman Panigrahi

Reputation: 633

Import .dat file spread over several lines into an 1D array in python

I have a .dat file that looks like the following.

[1.         0.99999999 0.99999975 0.9999908  0.99986024 0.99899004
 0.99591797 0.98880885 0.98462882 0.97393692 0.9566383]

I want to import it into an one dimensional array, [1,0.99999999,....,0.9566383].

I tried the following from this question.

with open('data.dat', 'r') as file:
    data = file.read().replace('\n', '')

print(data)

I cannot convert the string data into float, because all the digits, spaces and decimal points are going into the string. How do I ensure that the numbers like 0.99999975 are clubbed together (so that 0,.,9,9,...5 are not different entries), and the spaces are not counted as entries?

Upvotes: 0

Views: 75

Answers (1)

Lecdi
Lecdi

Reputation: 2241

After removing the first and last character (square brackets), all that is left to do is split the string up based on white spaces and convert each value to a float.

Here is the code:

with open('data.dat', 'r') as file:
    data_str = file.read()
data_str = data_str[1:-1]  # [1:-1] gets the string without its first and last characters
data = []
for num in data_str.split():  # .split(char) splits the string into a list based on the given character, which defaults to spaces and newlines when no character is given
    if num:
        data.append(float(num))

print(data)

This could also be done on a single line using a list comprehension, although the above solution is clearer.

Single line code:

with open('data.dat', 'r') as file: data = [float(i) for i in file.read()[1:-1].split() if i]

Upvotes: 1

Related Questions