I’m just learning Python to make extensions in Inkscape, and I’m having an issue with comparing strings that I loaded from a file. What I’m trying to do is to load a polygon that I have defined in a text file:
polygon
r:255
g:0
b:0
50;50
50;100
100;50
My parsing method is such:
def load_file(filepath, parent, log):
file = open(filepath)
x = []
y = []
r = 0
g = 0
b = 0
index = 0
for line in file:
fline = line.lstrip("\xef\xbb\xbf").rstrip("\n")
log.write("Input string: " + repr(line) + "\n")
log.write("Formatted: " + repr(fline) + "\n")
if fline == "":
continue
elif fline is "polygon": ## Where the first line should be going
log.write("\tDetected string as polygon start delimiter\n")
if index > 0:
draw_shape(x, y, r, g, b, "Polygon", parent)
del x[0, len(x)]
del y[0, len(y)]
r = g = b = index = 0
continue
elif fline[:2] is "r:":
log.write("\tDetected string as polygon red value delimiter\n")
r = int(fline[2:])
continue
elif fline[:2] is "g:":
log.write("\tDetected string as polygon green value delimiter\n")
g = int(fline[2:])
continue
elif fline[:2] is "b:":
log.write("\tDetected string as polygon blue value delimiter\n")
b = int(fline[2:])
continue
else: ## Where the first line actually is going
log.write("\tDelimiter failed previous detections; assumed to be polygon cordinates\n")
spl = fline.split(";")
x[index] = float(spl[0]) ## Error gets thrown here
y[index] = float(spl[1])
index += 1
continue
draw_shape(x, y, r, g, b, parent)
This method is tripping up on the first line. It keeps seeing “polygon” and going to the final else block, where it parses the coordinates. The log file I’m keeping throughout looks like this:
Process Started
Input string: '\xef\xbb\xbfpolygon\n'
Formatted: 'polygon'
Delimiter failed previous detections; assumed to be polygon coordinates
I’ve stepped through the process in the shell and in there it says line is "process" is true, so I am completely lost here. Any help?
The comparison
fline is "polygon"will almost always be false. Usefline == "polygon"instead.It’s unrelated to your problem, but you’ll have an easier time processing the text if you use the proper Unicode decoding functions, instead of manually stripping the byte order mark and treating the rest as bytes. I prefer
codecs.open(filename, encoding='utf-8-sig').