Вопрос

When I run the program, I get ValueError. I don't know why that is. The program is:

    def get_coordinates(infile, delimiter):
        new_list = []
        with open(infile, 'r') as f:
            for line in f:
                x, y = [float(i) for i in line.strip().split('delimiter')]


        new_list.append('%0.4f,%0.4f' % (x, y))

return new_list


LIST1 = get_coordinates('table1.txt', ',')
LIST2 = get_coordinates('table2.txt', ',')

NEW_LIST = list(set(LIST1) & set(LIST2))


with open('outfile.txt', 'w') as outfile:
    for xy in NEW_LIST:

        outfile.write('%s\n' % xy)

I get the following:

ValueError 

    202             else:
    203                 filename = fname
--> 204             __builtin__.execfile(filename, *where)


---> 18 LIST1 = get_coordinates('table1.txt', ',')
     19 LIST2 = get_coordinates('table2.txt', ',')
     20 


      7     with open(infile, 'r') as f:
      8         for line in f:
----> 9             x, y = [float(i) for i in line.strip().split('delimiter')]

222.27515,  8.0208306eral for float(): 222.30777,  8.9363889
Это было полезно?

Решение

You are seeing this because there is an error in your logic and/or code for pulling the floats out of the lines from your file. This is resulting in a call to float() that looks something like this:

>>> float('222.30777,  8.9363889')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 222.30777,  8.9363889

Currently you are trying to split each line on the string 'delimiter', so for example 'FOOdelimiterBAR'.split('delimiter') would result in ['FOO', 'BAR'].

From looking at the error message it looks like the floats are separated by a comma, so if you have a variable named delimiter then you should use line.strip().split(delimiter), or just use line.strip().split(',') if you know you want to be splitting on comma.

Другие советы

Try without the quotes around delimiter

x, y = [float(i) for i in line.strip().split(delimiter)]

You are trying to use the string 'delimiter' as the splitting char, not what the variable delimiter contains.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top