Fix .encode error and writeout missing imports