如何使用Python将 list 写入一个 txt 文件


一个数据list of dict如下

a = [
    {"Jodie1": "123"},
    {"Jodie2": "456"},
    {"Jodie3": "789"},
    ]

写入到本地一个txt文件,内容格式如下:

Jodie1,123
Jodie2,456
Jodie3,789 """

import re
import json

a = [
    {"Jodie1": "123"},
    {"Jodie2": "456"},
    {"Jodie3": "789"},
    ]

方法一

with open('1.txt', 'w') as f:
    for i in range(len(a)):
        for key, values in a[i].items():
            print(key+","+values+"\r")
            f.write(key+","+values+"\r")

方法二

file = open('2.txt', 'w')
for i in range(len(a)):
    s = str(a[i]).replace('{', '').replace('}', '').replace("'", '').replace(':', ',') + '\n'
    file.write(s)
file.close()

方法三

file3 = open('3.txt', 'w')
for i in range(len(a)):
    s = (re.sub(r"['{ },]*", '', str(a[i])) + '\n').replace(':', ',')
    file3.write(s)
file3.close()

方法四

with open('4.txt', 'w') as f:
    for i in range(len(a)):
        s = (re.sub(r"['{ },]*", '', str(a[i])) + '\n').replace(':', ',')
        f.write(s)

Python:将 list 写入一个 txt 文件四种方法介绍到这里,更多Python学习请参考编程字典Python教程 和问答部分,谢谢大家对编程字典的支持。


原文链接:https://www.cnblogs.com/djdjdj123/p/13788543.html