Python: ValueError: cannot convert string to float: '0'

For some school assignments, I tried to get pyplot to build some scientific graphs based on Logger Pro data for me. I met a mistake

ValueError: could not convert string to float: '0'

This program:

plot.py
-------------------------------
import matplotlib.pyplot as plt 
import numpy as np

infile = open('text', 'r')

xs = []
ys = []

for line in infile:
    print (type(line))
    x, y = line.split()
    # print (x, y)
    # print (type(line), type(x), type(y))

    xs.append(float(x))
    ys.append(float(y))

xs.sort()
ys.sort()

plt.plot(xs, ys, 'bo')
plt.grid(True)

# print (xs, ys)

plt.show()

infile.close()

And the input file contains the following:

text
-------------------------------
0 1.33
1 1.37
2 1.43
3 1.51
4 1.59
5 1.67
6 1.77
7 1.86
8 1.98
9 2.1

This is the error message that I get when starting the program:

Traceback (most recent call last):
  File "\route\to\the\file\plot01.py", line 36, in <module>
    xs.append(float(x))
ValueError: could not convert string to float: '0'
+4
source share
1 answer

Your data file has a UTF-8 specification; this is what my interactive Python 2 session states convert to float:

>>> '0'
'\xef\xbb\xbf0'

\xef\xbb\xbf - UTF-8 U + FEFF ZERO WIDTH NO-BREAK SPACE, Microsoft. UTF-8 , , UTF-16 UTF-32; Microsoft .

Python 3 utf-8-sig; :

infile = open('text', 'r', encoding='utf-8-sig')

Python 2 codecs.BOM_UTF8 ;

for line in infile:
    if line.startswith(codecs.BOM_UTF8):
        line = line[len(codecs.BOM_UTF8):]
    x, y = line.split()

codecs :

UTF-8 8- , , U+FEFF ( ) ZERO WIDTH NO-BREAK SPACE.

, . charmap . UTF-8, UTF-8 , . , UTF-8, Microsoft UTF-8 ( Python 2.5 "utf-8-sig") "": , , UTF-8 ( : 0xef, 0xbb, 0xbf). , charmap (, ,

LATIN SMALL LETTER I WITH DIAERESIS
RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
INVERTED QUESTION MARK

iso-8859-1), , a utf-8-sig . , , , , . utf-8-sig 0xef, 0xbb, 0xbf . utf-8-sig , . UTF-8 , , .

+5
source

All Articles