PYTHON将list或/dict对象写入txt/json文件

不能直接将list或dict对象进行写入,会出现typeError。

一、写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()

二、写dict对象到json文件

需要import json,将dict转为字符串后写入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)