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

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.

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

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?

>Solution :

After replacing newlines with spaces and 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.replace('\n', '')[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 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().replace('\n', '')[1:-1].split() if i]
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