zoukankan      html  css  js  c++  java
  • Python:将 list 写入一个 txt 文件

    # coding:utf-8
    """ 一个数据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+"
    ")
                f.write(key+","+values+"
    ")
    
    
    
    # 方法二
    file = open('2.txt', 'w')
    for i in range(len(a)):
        s = str(a[i]).replace('{', '').replace('}', '').replace("'", '').replace(':', ',') + '
    '
        file.write(s)
    file.close()
    
    
    
    # 方法三
    file3 = open('3.txt', 'w')
    for i in range(len(a)):
        s = (re.sub(r"['{ },]*", '', str(a[i])) + '
    ').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])) + '
    ').replace(':', ',')
            f.write(s)
  • 相关阅读:
    ebs R12 支持IE11
    reloc: Permission denied
    3.23考试小记
    3.21考试小记
    3.20考试小记
    3.17考试小记
    3.15考试小记
    3.13考试小记
    3.12考试小记
    3.10考试小记
  • 原文地址:https://www.cnblogs.com/JodieRao/p/12723615.html
Copyright © 2011-2022 走看看