0

I am quite new to python and extremely new to ASCII file reading :)

When I export the results from a simulation program I obtain an ASCII file in the form:

0,0000000E+0000 4,5000000E+0000

5,0000000E-0001 4,5063043E+0000

1,0000000E+0000 4,5117097E+0000

1,5000000E+0000 4,5188112E+0000

2,0000000E+0000 4,5230832E+0000

no headers! Each row contains two numbers (my "x" parameter and "y" parameter in the plot I want to generate). Despite the comma in place of the decimal point and the fact that the two parameters numbers are not divided into columns.

Can you help?

P.s. sorry for not providing a code example but they are all poorly wrong

AMaz
  • 181
  • 1
  • 2
  • 10
  • Possible duplicate of [Convert Python strings into floats explicitly using the comma or the point as separators](https://stackoverflow.com/questions/13362121/convert-python-strings-into-floats-explicitly-using-the-comma-or-the-point-as-se) – VPfB Apr 20 '18 at 15:39

1 Answers1

2

A more functional solution:

def convert_to_float(num_with_comma):
    return float(num_with_comma.replace(',', '.'))

with open('test.txt') as f:
    # we strip each line of its trailing '\n' and split it
    points = (line.strip().split() for line in f)
    # we convert the strings to floats if the string wasn't empty
    points = (map(convert_to_float, point) for point in points if point)
    # and separate the x and y coords
    x, y = zip(*points)

print(x, y)
# (0.0, 0.5, 1.0, 1.5, 2.0) (4.5, 4.5063043, 4.5117097, 4.5188112, 4.5230832)
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • You're welcome! If you feel that some answer you got for your question solves it, you can mark it as accepted (there's a tick mark near the answer) – Thierry Lathuille Apr 20 '18 at 18:18