0

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

4
  • 1
    It would help if you describe the format of your text file. Using eval to avoid \n is something indescribable.
    – khachik
    Dec 10, 2010 at 9:43
  • What is this code supposed to do? Dec 10, 2010 at 9:43
  • it takes some file.txt on my harddrive and imports the text to python shell as a string, so if the file for instant had 1,2 (newline) 2,3 (newline) 7,5 the input i get in shell is ['1,2\n', '2,3\n', '7,5'] and i want it to be numbers i can work with :) hope that helped
    – user457142
    Dec 10, 2010 at 9:47
  • ... So let's be clear: each line int the file has, as text, a comma-delimited list of integers on it, and you want to convert this text into a Python list of int objects? Dec 10, 2010 at 12:48

5 Answers 5

2

Hint:

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

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()
1

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

2
  • val = [float(line) for line in open('test.txt')] would be both clearer and more memory-efficient (because iterating through lines in a file doesn't read all the lines at once, unlike readlines()).
    – Ben Hoyt
    Dec 10, 2010 at 14:41
  • @benhoyt: You're right... I often end up using L=open(xxx).readlines() when I need to play with many lines at the same time and it's something that dangerously got to the finger level now.
    – 6502
    Dec 10, 2010 at 15:26
0

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

0

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.