I am trying to write backwards compatible code that involves reading some data from disk, that includes a UTF-8 string, process it as a string, then write it back to the disk. The only way that work for me is:
val=fh.read(n)
str(val.decode("utf-8"))
This seems really verbose, but everything else I try fails in either 2.x or 3.x. Is there a neater way to do it?
This will produce a byte array not a string on 3.x
str(val)
This fails on 2.x (no second argument)
str(val,"utf-8")
This fails when I try and write the value back to disk on 2.x ("expected string, got unicode"):
val.decode("utf-8")
Tried a couple of combinations but no luck. Is this really the only way to do it?