0
votes

I have an encoded string saved as a string in a file, it is possible to change that, if it works then. I wanna read it and get the real string back. Sorry I'm not good in explaining xD, here's my code:

def saveFile(src, con):
    with open(src, "w") as f:
        f.write(str(con))
        f.close()

...
string = "юра"
saveFile("info", mlistsaver.encode())

this is the 'info' File:` b'\xd1\x8e\xd1\x80\xd0\xb0' but when I use this:

def get(src):
    f = src
    if path.isfile(f):
        with open(f, "r") as f:
            return f.read()
    else:
        return None

...


get("info").encode('iso-8859-1').decode('utf-8')

the string is just: b'\xd1\x8e\xd1\x80\xd0\xb0' I know it has to do something with double \ but I couldn't fix it. As already said I can save the string in whatever format you want, I think the way I did it is really stupid.

Thank you guys!

1
you dont need to encode >>> b'\xd1\x8e\xd1\x80\xd0\xb0'.decode('utf-8') output: 'юра' - BpY
Don't call str() on the value you want to write to a file. If con is a bytes object, you will have the b'...' prefix+quotes literally in the output file, and also escape sequences with literal backslashes. If con is a byte string, open the file in binary mode (mode="wb") and directly write to it. - lenz

1 Answers

0
votes

Thank you very much BpY and lenz, it's working now, here's my code:

def saveFile(src, con):
    with open(src, "wb") as f:
        f.write(con)
        f.close()

def get(src):
    f = src
    if path.isfile(f):
        with open(f, "rb") as f:
            return f.read()
    else:
        return None

...

info="юра"
saveFile("info", info.encode())
print(get("info").decode("utf-8"))

Output is: юра

Again thank you and have a nice day:)