1. 程式人生 > >自動化測試-17.selenium數據的分離之txt文本的寫入與讀取

自動化測試-17.selenium數據的分離之txt文本的寫入與讀取

try 什麽 ioe 9.png spl 自動 except AI int

前言

  數據量偏小時,用txt文本保存數據比較合適,以-進行區分,為什麽不用:呢?原因是,我們在使用數據時,會存在url地址的情況,裏面寶行所以用-進行替代

此處附上代碼

 1 #encoding=utf-8
 2 
 3 def load_dict_from_file(filepath):
 4     _dict = {}
 5     try:
 6         with open(filepath, r) as dict_file:
 7             for line in dict_file:
 8                 (key, value) = line.strip().split(
-) 9 _dict[key] = value 10 except IOError as ioerr: 11 print "文件 %s 不存在" % (filepath) 12 13 return _dict 14 15 16 def save_dict_to_file(_dict, filepath): 17 try: 18 with open(filepath, w) as dict_file: 19 for (key, value) in _dict.items():
20 dict_file.write(%s-%s\n % (key, value)) 21 except IOError as ioerr: 22 print "文件 %s 無法創建" % (filepath) 23 24 25 if __name__ == __main__: 26 _dict = load_dict_from_file(dict.txt) 27 print _dict 28 save_dict_to_file(_dict, dict_copy.txt)

文本的存儲格式截圖為:

技術分享圖片

文件的寫入後的截圖為:

技術分享圖片

自動化測試-17.selenium數據的分離之txt文本的寫入與讀取