I am having a problem with the data I have collected. When I write the data to a file it is shown like this.

(231.2314,32434.344,134.2342,345.345,1234.45)

(2323.567,32.6754,12323.8776,12323.575,233.5673)

now when I read data and put it in a list it looks like this.

data = ['(231.2314,32434.344,134.2342,345.345,1234.45)
\n','(2323.567,32.6754,12323.8776,12323.575,233.5673)\n']

is there any way i can just retrieve the floats from the file. When I try to convert to float I get an error about '(' is not a float. Can someone point me into the right direction. I have attached the data. Thanks.

Here is one way you can approach your problem ...

import pprint

test_data = """\
(231.2314,32434.344,134.2342,345.345,1234.45)
(2323.567,32.6754,12323.8776,12323.575,233.5673)
"""
# write the test data file out
fname = "atest.txt"
fout = open(fname, "w")
fout.write(test_data)
fout.close()

# read the test data file back in
fin = open(fname, "r")
data_list1 = []
data_list2 = []
for line in fin:
    # strip whitespace
    line = line.strip()
    # strip '('
    line = line.strip('(')
    # srip ')'
    line = line.strip(')')
    #convert string to list of floats at the comma
    data_float = [float(x) for x in line.split(',')]
    # create a list of line sublists
    data_list1.append(data_float)
    # create one list of all data items
    data_list2.extend(data_float)

pprint.pprint( data_list1 )

print('-'*30)

pprint.pprint( data_list2 )

""" result (typical binary rep of floats) >>>
[[231.23140000000001,
  32434.344000000001,
  134.23419999999999,
  345.34500000000003,
  1234.45],
 [2323.567,
  32.675400000000003,
  12323.8776,
  12323.575000000001,
  233.56729999999999]]
------------------------------
[231.23140000000001,
 32434.344000000001,
 134.23419999999999,
 345.34500000000003,
 1234.45,
 2323.567,
 32.675400000000003,
 12323.8776,
 12323.575000000001,
 233.56729999999999]
"""

Some numbers look a little strange at first, but most computer languages handle floating point numbers as binary numbers which can introduce a very tiny error with some numbers.

Thanks a lot. Worked perfect and solved my problem. Thanks again

After some practise with Python idioms, you could maybe prefer this list comprehension:

test_data = """\
(231.2314,32434.344,134.2342,345.345,1234.45)
(2323.567,32.6754,12323.8776,12323.575,233.5673)
"""
data = [ tuple( float(string_data)
                for string_data in eval(data_tuple))
         for data_tuple in test_data.splitlines()
         if data_tuple.startswith('(')]

for data_tuple in data:
    print type(data_tuple[0]),data_tuple
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.