所有栏目 | 云社区 美国云服务器[国内云主机商]
你的位置:首页 > 云社区 » 正文

python将固定格式的文本转换成字典?

发布时间:2020-04-15 16:11:03

资讯分类:python  字典  转换成  文本  文件  内容  不存在
python将固定格式的文本转换成字典?

看代码,serial_dict.py:

1234567891011121314151617181920212223242526

# -*- encoding: gbk -*- def load_dict_from_file(filepath):    _dict = {}    try:        with open(filepath, 'r') as dict_file:            for line in dict_file:                (key, value) = line.strip().split(':')                _dict[key] = value    except IOError as ioerr:        print "文件 %s 不存在" % (filepath)         return _dict def save_dict_to_file(_dict, filepath):    try:        with open(filepath, 'w') as dict_file:            for (key,value) in _dict.items():                dict_file.write('%s:%sn' % (key, value))    except IOError as ioerr:        print "文件 %s 无法创建" % (filepath) if __name__ == '__main__' :    _dict = load_dict_from_file ('dict.txt')    print _dict    save_dict_to_file(_dict, 'dict_copy.txt')

dict.txt 的内容:

运行:

dict_copy.txt 的内容:

留言与评论(共有 0 条评论)
   
验证码:
Top