python保存数据到本地文件的方法

1、保存列表为.txt文件

#1/list写入txt

ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21'] 
fileObject = open('sampleList.txt', 'w') 
for ip in ipTable: 
 fileObject.write(ip) 
 fileObject.write('\n') 
fileObject.close() 

2、字典保存

#2/dict写入json
import json

dictObj = { 
 'andy':{ 
  'age': 23, 
  'city': 'shanghai', 
  'skill': 'python' 
 }, 
 'william': { 
  'age': 33, 
  'city': 'hangzhou', 
  'skill': 'js' 
 } 
} 

jsObj = json.dumps(dictObj) 

fileObject = open('jsonFile.json', 'w') 
fileObject.write(jsObj) 
fileObject.close() 

以上这篇python保存数据到本地文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。