Python--——檔案讀寫
阿新 • • 發佈:2018-12-23
一.檔案寫操作 import pickle
三步:(1)開:檔案變數 = open(“檔案路徑檔名”,“wb”)
(2)存:pickle.dump(“待寫入的變數”,“檔案變數“)
(3)關:檔案變數.close()
程式碼如下:
Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> game_data = {"position":"N2 E3","age":18} >>> save_file = open("a.data","wb") >>> pickle.dump(game_data,save_file) >>> save_file.close() >>> exit()
二.檔案讀操作 import pickle
三步:(1)開:檔案變數 = open(”檔案路徑檔名“,”rb“)
(2)取:放內容的變數 = pickple.load(檔案變數)
(3)關:檔案變數.close()
程式碼如下:
Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> load_file = open("a.data","rb") >>> load_game_data = pickle.load(load_file) >>> load_file.close() >>> load_game_data {'position': 'N2 E3', 'age': 18}