zoukankan      html  css  js  c++  java
  • python数据文件读写

    CSV格式读写

    Comma-Separated Values 有时也称为字符分隔值,因为分隔字符也可以不是逗号。以,分隔的文件叫csv,以 分隔的叫tsv

    需要注意的一点:分隔符

    import csv 
    
    data=[]
    with open(r'data.csv',) as csvfile:
        file_list = csv.reader(csvfile,'mydialect')
        for line in file_list:
            data.append(line)
    print(data)
    

    如果文件是其他分隔符,如 ,则需要传入分隔符类型。

    import csv 
    
    data=[]
    with open(r'data.csv',) as csvfile:
        file_list = csv.reader(csvfile,delimiter='	')
        for line in file_list:
            data.append(line)
    print(data)
    

    读取

    列表方式读取

    import csv
    
    with open('data.csv','r',encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            # 读取出的内容是列表格式的
            print(row,type(row),row[1])
    

    字典方式读取

    import csv
    
    with open('data.csv','r',encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            # 读取的内容是字典格式的
            print(row['last_name'])
    

    写入

    列表方式写入

    import csv
    
    with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
        writer = csv.writer(csvfile)
    
        # 写入一行 
        writer.writerow(['1','2','3','4','5','5','6'])
    
        # 写入多行
        writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
    

    字典方式写入

    import csv
    with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:
        filename = ['first_name','last_name']
        # 写入列标题
        writer = csv.DictWriter(csvfile,fieldnames=filename)
        writer.writeheader()
        writer.writerow({'first_name':'wl','last_name':'wtx'})
        writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
        writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
    

    json格式读写

    python内置json包提供了四个函数:dumps、dump、loads、load。不带s的负责文件与字典的转换。带s的负责字符串和字典的转换。

    字典到字符串 string json.dumps(dict)

    import json
    
    test_str = json.dumps({'name' : "cat"})
    

    字符串到字典 dict json.loads(string)

    import json
    
    test_dict = json.loads("{'name' : "cat"}")
    

    字典到json文件 json.dump(dict, file)

    import json
    
    with open("test.json","w") as f:
        json.dump({'name' : "cat"}, f)
    

    json文件到字典 dict json.load(file)

    import json
    
    with open("test.json",'r') as f:
        test_dict = json.load(f)
    
    文有疏漏,请大家批评指正!
  • 相关阅读:
    [原创]RTX使用printf输出后进入hardfault中断的处理方法
    [原创]单片机 HexToStr and HexToBcd BcdToStr
    [原创]单片机-HexToStr or HexToAsc
    再看 AspriseOCR
    [源创] STM32F103ZET6 基于XMODEM 通讯的 BOOTLOADER案列IAP
    单片机串口——如何判定接收一帧数据的完成
    [原创] 关于步科eview人机界面HMI的使用
    [原创] STM32 定时器TIMx 编码器应用 函数 TIM_EncoderInterfaceConfig 分析
    单片机的 HexToStr HexToBcd BcdToStr 几个转换函数
    [转载] 全局键盘钩子(WH_KEYBOARD)
  • 原文地址:https://www.cnblogs.com/trialley/p/10474007.html
Copyright © 2011-2022 走看看