• 几种数据格式的处理


    1. CSV数据

     
    import csv
     
    csvfile = open('data_text.csv','rb')
    reader = csv.reader(csvfile)           # 返回数据为列表类型
    # reader = csv.DictReader(csvfile)     #返回数据为字典类型
     
    for row in reader:
        print (row) 
     

     

     

     

     

    2.JSON数据

    import json
     
    json_data = open('data_text.json').read()
    data = json.load(json_data)
     
    for item in data:
        print(item)

     

     

    3. XML数据

     本例中使用的是ElementTress库,也可以使用lxml库和minidom库处理xml数据。

    from xml.etree import ElementTree as ET
     
    tree = ET.parse('data_text.xml')
    root = tree.getroot()
     
    data = root.find('Data')
     
    all_data = []
     
    for observation in data:
        record = {}
        for item in observation:
            lookup_key = item.attrib.keys()[0]
            
            if lookup_key== 'Numeric':
                rec_value = item.attrib['Numeric']
            else :
                rec_key = item.attrib[lookup_key]
                rec_value = item.attrib['Code']
                
            record[rec_key] = rec_value
            
        all_data.append(record)
        
    print all_data
     

     

     

     4. Excel数据

    处理Excel需要安装第三方库:

    xlrd :读取Excel文件

    xlwt:向Excel文件写入,并设置格式

    xlutils:一组Excel高级操作工具(需要先安装xlrd和xlwt)

     

    import xlrd
    
    book = xlrd.open_workbook('data_text.xlsx')
    
    for sheet in book.sheets():
        print sheet.name
    
    sheet = book.sheet_by_name('Table_9')
    
    data = {}
    
    for i in xrange(14,sheet.nrows):
        row = sheet.row_values(i)

     

     

  • 相关阅读:
    OC-为何用copy修饰block
    OC-RunLoop运行循环
    苹果审核之遇到IPV6问题被拒的解决方法
    LeetCode学习_day1:原地算法
    OC-加载h5富文本的代码,并计算高度
    OC-bug: Undefined symbols for architecture i386: "_OBJC_CLASS_$_JPUSHRegisterEntity", referenced from:
    了解iOS各个版本新特性总结
    iOS 快速打包方法
    iOS tableView侧滑删除的第三方控件
    Object_C 集成环信时,中文环境下不显示中文
  • 原文地址:https://www.cnblogs.com/gforc/p/7399230.html
Copyright © 2020-2023  润新知