ホームページ  >  記事  >  バックエンド開発  >  Python の解析では、pickle モジュールを使用して、追加、削除、変更、検索などのいくつかの機能を実行します。

Python の解析では、pickle モジュールを使用して、追加、削除、変更、検索などのいくつかの機能を実行します。

巴扎黑
巴扎黑オリジナル
2017-08-09 10:56:131731ブラウズ

この記事ではPythonのpickleモジュールを使った「追加、削除、変更、確認」の簡単な機能を中心に紹介していますので、興味のある方は参考にしてみてください。

pickle の役割:

1: pickle.dump(dict,file) は辞書をバイナリに変換し、ファイルに保存します。

2: pickle.load(file) はファイルのバイナリコンテンツを辞書


import pickle

# 增 
def adds(): 
  users = {"name":"yangbin", "age":22, "sex":"male"} 
  with open("red.txt", "wb") as f: 
    pickle.dump(users, f)
  dic = {} 
  with open("red.txt") as sd: 
    dic = pickle.load(sd) 
  print dic

# 删 
def deletes():
  dic = {} 
  with open("red.txt") as f: 
    dic = pickle.load(f)
  dic.pop("sex")
  with open("red.txt", "wb") as ff: 
    pickle.dump(dic, ff) 
  print dic 

# 改 
def changes(): 
  dic = {}
  with open("red.txt") as f: 
    dic = pickle.load(f) 
  dic["age"] = 28 
  with open("red.txt", "wb") as f: 
    pickle.dump(dic, f) 
  print dic

# 查 
def finds(): 
  dic = {}
  with open("red.txt") as f: 
    dic = pickle.load(f) 
  for k,v in dic.items():
    print "%s ---> %s" % (k, v) 

adds() 
deletes() 
changes()
finds()

実行結果:


root@python3:/python/python2/linshi# python 01.py 
{'age': 22, 'name': 'yangbin', 'sex': 'male'}
{'age': 22, 'name': 'yangbin'}
{'age': 28, 'name': 'yangbin'}
age ---> 28
name ---> yangbin
root@python3:/python/python2/linshi#

以上がPython の解析では、pickle モジュールを使用して、追加、削除、変更、検索などのいくつかの機能を実行します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。