0

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?

3
  • Have you tried stripping the first and the last character and then splitting on whitespace? And then converting each part to a float? Commented Apr 10, 2022 at 16:10
  • How do I split whitespaces? Also, consider the the number 0.97393692. Here, "0", ".", "9", "7", etc. are being saved in different indices of data. How do I ensure that the number 0.97393692 is taken as a single "part"? Commented Apr 10, 2022 at 16:18
  • stackoverflow.com/questions/8113782/… Commented Apr 10, 2022 at 17:24

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.