python将一个txt文档的内容转为字典格式/将字典格式存储到txt文档中

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaomifanhxx/article/details/81672409
# -*- 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:%s\n' % (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')

猜你喜欢

转载自blog.csdn.net/xiaomifanhxx/article/details/81672409