Python: Four methods to write list into a txt file

A data list of dict is as follows

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

Write to a local txt file, the content format is as follows:

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

import re
import json

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

method one

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")

Method Two

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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()

Method Three

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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()

Method Four

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)

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108979354