python读取/写入list/dict对象为txt/json文件

将list对象写入txt文件

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

list1 = ['1','2','3','4']
fileObject = open('list.txt','w')
for word in list1:
    fileObject.write(word)
    fileObject.write('\n')
fileObject.close()

将txt文件读出

读出

这里用open函数读取了一个txt文件,”encoding”表明了读取格式是“utf-8”,还可以忽略错误编码。
另外,使用with语句操作文件IO是个好习惯,省去了每次打开都要close()。

with open("list.txt","r",encoding="utf-8",errors='ignore') as f:
    data = f.readlines()
    for line in data:
        word = line.strip() #list
        print(word)

读为numpy的数组,可以进一步转换为list对象

array_ = numpy.loadtxt('list.txt')
list_ = list(array_) 

将dict对象写入json文件

需要import json,将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()  

读取json文件

with open('data.json', 'r') as f:
    data = json.load(f)

写入json文件

with open('data.json', 'w') as f:
    json.dump(data, f)

你可能感兴趣的:(python读取/写入list/dict对象为txt/json文件)