1. 程式人生 > >Python進階-pickle/eval/exec

Python進階-pickle/eval/exec

acc The imp exec class exce .com com this

  • 參考:
    •   eval/exec/compile的區別:https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python
    •   pickle的使用: https://pythontips.com/2013/08/02/what-is-pickle-in-python/
  • 背景
    • 之前用打印到文件,逐行讀出用eval轉換格式。現在用pickle可直接實現。
  • pickle_eval_exec的區別:
    • pickle: dump到file, 從file中load
    • eval: eval accepts only a single expression, eval
      returns the value of the given expression。
    • exec: exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on. return None.
  • Pickle的使用:(pickle.load(), pickle.dump())
import pickle

a = [test value,test value 2,test value 3]
a
[
test value,test value 2,test value 3] file_Name = "testfile" # open the file for writing fileObject = open(file_Name,wb) # this writes the object a to the # file named ‘testfile‘ pickle.dump(a,fileObject) # here we close the fileObject fileObject.close() # we open the file for reading fileObject = open(file_Name,
r) # load the object from the file into var b b = pickle.load(fileObject) b [test value,test value 2,test value 3] a==b True

Python進階-pickle/eval/exec