Unicode issue
SolvedHello
I have a problem with the retrieval of a .yg
"C:\Program Files\Python311\python.exe" C:\Users\Gwenneg\PycharmProjects\pickle2\main.py File "C:\Users\Gwenneg\PycharmProjects\pickle2\main.py", line 7 fil=open("C:\Users\Gwenneg\PycharmProjects\pythonProject1\saved.yg","rb") ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Process finished with exit code 1
Thank you
6 answers
Hello,
This is not how you use pickle: you don't do pickle.dump(), then open and write to
the file, you dump directly:
with open('saved.yg','wb') as fo: pickle.dump(saved, fo) And for reading:
with open('saved.yg','rb') as fo: saved = pickle.load(fo)
Hello,
Regarding your response #2, I have never seen the yg extension (pkl seems more natural to me), but why not.
Then, in addition to Phil_1857's response #3, here’s how you can do it.
Code:
import pickle from types import ModuleType def save_all(filename: str): with open(filename, "wb") as f: g = { k : v for (k, v) in globals().items() if ( not (k.startswith("__") and k.endswith("__")) and not callable(v) and not isinstance(v, ModuleType) ) } pickle.dump(g, f) def load_all(filename: str): with open(filename, "rb") as f: for (k, v) in pickle.load(f).items(): globals()[k] = v # Prepare the pickle filename = "toto.pkl" a = 1234567 print(f"saving {filename}") save_all("toto.pkl") # Delete the global variable "a" print("del a") del a try: print(f"a = {a}") except Exception as e: print(e) # Load the pickle print(f"loading {filename}") load_all(filename) print(f"a = {a}") Result
saving toto.pkl del a name 'a' is not defined loading toto.pkl a = 1234567 Good luck
Hello,
The question is too vague.
- What is a yg file?
- How did you create it?
- How are you trying to open it?
Good luck
Hello
1. It is a binary file extension
2. I did it using the following code:
import pickle def sauvonstout(): globs = list(globals()) saved = [] for v in globs: d = globals()[v] t = (str(type(d))) if t != "<class 'module'>" and t !="<class 'function'>": saved.append((v,pickle.dumps(d))) bytessaved = pickle.dumps(saved) fil = open("saved.yg","wb") fil.write(bytessaved) fil.close() a=1234567 sauvonstout() 3. Using the following code:
import pickle def restore(pb): b = pickle.loads(pb) for n, p in b: v = pickle.loads(p) globals()["yg"+n] = pickle.loads(p) fil = open("saved.yg","rb") pb = fil.read() restore(pb) print(yga)