Discuss / Python / 交作业

交作业

Topic source
import pickle,json

#```pickle```
a = "即使你遗忘了我,我也不会遗忘你"

with open("C://Users//Administrator//Desktop//hello.txt",'wb') as f:
    pickle.dump(a,f)
    print(pickle.dumps(a))

with open("C://Users//Administrator//Desktop//hello.txt",'rb') as f:
    print(pickle.load(f))


#```json```

b = "请继续向前,迎接樱花漫溢的四月,但请不要忘记我."

with open("C://Users//Administrator//Desktop//world.txt",'w') as x:
    json.dump(b,x)
    print(json.dumps(b))

with open("C://Users//Administrator//Desktop//world.txt",'r') as x:
    print(json.load(x))


class Book:
    def __init__(self,name,age,score):
        self.name = name 
        self.age = age 
        self.score = score

def dict_book(poi):
    return {"name":poi.name,"age":poi.age,"score":poi.score}

a = open("C://Users//Administrator//Desktop//hello_world.txt",'w')
x = json.dumps(Book("Bob",20,88),default=dict_book)
print(x)

with open("C://Users//Administrator//Desktop//hello_world.txt",'w') as f:
    json.dump(x,f)
    print(json.dumps(x))

with open("C://Users//Administrator//Desktop//hello_world.txt",'wb') as e:
    pickle.dump(x,e)
    print(pickle.dumps(x))

输出:

b'\x80\x03X-\x00\x00\x00\xe5\x8d\xb3\xe4\xbd\xbf\xe4\xbd\xa0\xe9\x
81\x97\xe5\xbf
\x98\xe4\xba\x86\xe6\x88\x91\xef\xbc\x8c\xe6\x88\x91\xe4\xb9\x9f\xe4\xb8\x8d\xe4
\xbc\x9a\xe9\x81\x97\xe5\xbf\x98\xe4\xbd\xa0q\x00.'
即使你遗忘了我,我也不会遗忘你
"\u8bf7\u7ee7\u7eed\u5411\u524d\uff0c\u8fce\u63a5\u6a31\u82b1\u6f2b\u6ea2\u7684\
u56db\u6708\uff0c\u4f46\u8bf7\u4e0d\u8981\u5fd8\u8bb0\u6211."
请继续向前,迎接樱花漫溢的四月,但请不要忘记我.
{"name": "Bob", "score": 88, "age": 20}
"{\"name\": \"Bob\", \"score\": 88, \"age\": 20}"
b'\x80\x03X\'\x00\x00\x00{"name": "Bob", "score": 88, "age": 20}q\x00.'
`

  • 1

Reply