Python将字典类型数据一行行写入文件并读取出来

说明:

  1. json.dumps()用于将字典形式的数据转化为字符串。
  2. json.loads()用于将字符串形式的数据转化为字典。
  3. 函数convertFileFmt用于将Windows(CR LF)格式的文件转换为Unix(LF)格式。

参考小例:

# -*- coding: utf-8 -*-
import os
import json
import time


def writeDict2File(fileName):
    print('start write ...')
    dictList = [
        {1: 'a', 2: 'b', 3: 'c'},
        {11: 'aa', 22: 'bb', 3: 'cc'},
        {111: 'aaa', 222: 'bbb', 333: 'ccc'}
    ]

    with open(fileName, 'w', encoding='utf-8') as f:
        for oneData in dictList:
            js = json.dumps(oneData, ensure_ascii=False)
            f.write(js)
            f.write('\n')
    convertFileFmt(fileName)
    print('Write OK')


def readFile2Dict(fileName):
    print('start read ...')
    dictList = []
    with open(fileName, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            js = json.loads(line.strip(), encoding='utf-8')
            dictList.append(js)
    print(dictList)
    for oneData in dictList:
        print(oneData)
    print('Read OK')


def convertFileFmt(fileName):
    with open(fileName, 'rb') as fr:
        content = fr.read()
        content = content.replace(b'\r\n', b'\n')
        print(content)

    with open(fileName, 'wb') as fw:
        fw.write(content)


if __name__ == '__main__':
    fileName = os.path.join(os.getcwd(), 'lalala.txt')
    writeDict2File(fileName)
    time.sleep(3)
    readFile2Dict(fileName)

输出结果如下

start write ...
b'{"1": "a", "2": "b", "3": "c"}\n{"11": "aa", "22": "bb", "3": "cc"}\n{"111": "aaa", "222": "bbb", "333": "ccc"}\n'
Write OK
start read ...
[{'1': 'a', '2': 'b', '3': 'c'}, {'11': 'aa', '22': 'bb', '3': 'cc'}, {'111': 'aaa', '222': 'bbb', '333': 'ccc'}]
{'1': 'a', '2': 'b', '3': 'c'}
{'11': 'aa', '22': 'bb', '3': 'cc'}
{'111': 'aaa', '222': 'bbb', '333': 'ccc'}
Read OK

你可能感兴趣的:(Python基础,python,json)