user457142
user457142

Reputation: 267

the Eval function in Python

Hello there i have the following code:

path = some destination on your harddrive

def K(path):
    try:

        getfile = open(path + '/test.txt')
        line = getfile.readlines()
        print line
        getfile.close()

    except:
        line = getfile.readlines()
        eval(line)
        d = dict()
        val= d[k]

to import a textfile, now my problem is to avoid the \n, which i assume can be done using the eval() function. I want to convert the string i get as input, to floats i can work with..

Thanx for any tips in advance

Upvotes: 0

Views: 1660

Answers (5)

6502
6502

Reputation: 114461

your code is quite confused... to read a file that contains one float per line you can simply do:

val = map(float, open("test.txt"))

val will be a list containing your data with each element being a float

Upvotes: 1

Ben Hoyt
Ben Hoyt

Reputation: 11044

Here's a function read_numbers() which returns a list of lists of floats.

def read_numbers(filename):
    numbers = []
    with open(filename) as f:
        for line in f:
            lst = [float(word) for word in line.split(',')]
            numbers.append(lst)
    return numbers

If your file contains:

1, 2
2, 3
7, 5

Then read_numbers('filename') would return:

[[1.0, 2.0], [2.0, 3.0], [7.0, 5.0]]

You may want to do error handling (or simply ignore errors) by expanding out the inner list comprehension and wrapping the call to float() in a try ... except ValueError.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

ast.literal_eval() will turn each line into tuples that you can then iterate or index for the values.

Upvotes: 0

khachik
khachik

Reputation: 28703

I won't comment your code, just will post an example you can examine and modify to get it working. This function reads the content of a text file and converts tokens separated by whitespaces to floats if possible:

def getFloats(filepath):
  fd = open(filepath) # open the file
  try:
    content = fd.read().split() # read fully
    def flo(value):  # a function that returns a float for the given str or None
      try: return float(value)
      except ValueError: return None # skip invalid values
    # iterate through content and make items float or None,
    # iterate over the result to choose floats only
    return [x for x in [flo(y) for y in content] if x]
  finally:
    fd.close()

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156138

Hint:

>>> float("\n1234\n")
1234.0

Upvotes: 2

Related Questions