python-常用方法记录
1.读取txt数据,通过for循环,读取每一行数据作为列表,然后把列表变成字典显示
数据样例:
张三:0
李四:0
王五:0
name_dict = {}
def read_txt(): with codecs.open(filename,'r','utf-8') as fp: data = fp.readlines() name_dict = {} print(data) for line in data: name_score = line.replace('\r\n', '').split(':') name_dict[name_score[0]] = name_score[1] return name_dict
输出:
{'张三': '0', '李四': '0', '王五': '0'}