Python的I/O操作与Json操作

    with open('in.txt', 'r') as fileIn:
        text = fileIn.read()

    word_count = parse(text)

    with open('out.txt', 'w') as fileOut:
        for word, count in word_count:
            fileOut.write('{} {}\n'.format(word, count))

open()函数 对应于 close()函数,正常情况下,打开了文件,需要关闭。
如果使用了with语句,就不需要显式的调用 close,close函数会被自动的调用

Json转换

将字典dict转换成json字符串
json.dumps() 接收json类型,转换成json字符串
json.loads() 接收json字符串, 转换成json类型

import json
params = {
    'symbol': '123456',
    'type': 'limit',
    'price': 123.4,
    'amount': 23
}

params_str = json.dumps(params)
print(type(params_str))
print(params_str)


{"symbol": "123456", "type": "limit", "price": 123.4, "amount": 23}

将json字符串 转换成 字典dict

params_dict = json.loads(params_str)

print(type(params_dict))
print(params_dict)


{'symbol': '123456', 'type': 'limit', 'price': 123.4, 'amount': 23}

在测试中,出现了个小问题

AttributeError: partially initialized module 'json' has no attribute 'dumps' (most likely due to a circular import)

错误提示.png

看到错误提示,才发现我的这个测试文件名字是json.py,而第一行是import json,相当于自己引用自己,循环引用
解决方法:修改文件名

你可能感兴趣的:(Python的I/O操作与Json操作)