import os
import sys
import argparse

try:
    import cStringIO as StringIO
except:
    import StringIO
import struct
import json
import csv

def import_data(import_file):
    '''
    Imports data from import_file.
    Expects to find fixed width row
    Sample row: 161322597 0386544351896 0042
    '''
    mask = '9s14s5s'
    data = []
    with open(import_file, 'r') as f:
        for line in f:
            # unpack line to tuple
            fields = struct.Struct(mask).unpack_from(line)
            # strip any whitespace for each field
            # pack everything in a list and add to full dataset
            data.append(list([f.strip() for f in fields]))
    return data

def write_data(data, export_format):
    '''
    Dispatches call to a specific transformer
    and returns data set.
    Exception is xlsx where we have to save data in a file.
    '''
    if export_format == 'csv':
        return write_csv(data)
    elif export_format == 'json':
        return write_json(data)
    elif export_format == 'xlsx':
        return write_xlsx(data)
    else:
        raise Exception("Illegal format defined")

def write_csv(data):
    '''
    Transforms data into csv.
    Returns csv as string.
    '''
    # Using this to simulate file IO,
    # as csv can only write to files.
    f = StringIO.StringIO()
    writer = csv.writer(f)
    for row in data:
        writer.writerow(row)
    # Get the content of the file-like object
    return f.getvalue()

def write_json(data):
    '''
    Transforms data into json.
    Very straightforward.
    '''
    j = json.dumps(data)
    return j

def write_xlsx(data):
    '''
    Writes data into xlsx file.
    
    '''
    from xlwt import Workbook
    book = Workbook()
    sheet1 = book.add_sheet("Sheet 1")
    row = 0
    for line in data:
        col = 0
        for datum in line:
            print datum
            sheet1.write(row, col, datum)
            col += 1
        row += 1
        # We have hard limit here of 65535 rows
        # that we are able to save in spreadsheet.
        if row > 65535:
            print >> sys.stderr, "Hit limit of # of rows in one sheet (65535)."
            break
    # XLS is special case where we have to
    # save the file and just return 0
    f = StringIO.StringIO()
    book.save(f)
    return f.getvalue()
   
   
if __name__ == '__main__':
    # parse input arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("import_file", help="Path to a fixed-width data file.")
    parser.add_argument("export_format", help="Export format: json, csv, xlsx.")
    args = parser.parse_args()

    if args.import_file is None:
        print >> sys.stderr, "You myst specify path to import from."
        sys.exit(1)

    if args.export_format not in ('csv','json','xlsx'):
        print >> sys.stderr, "You must provide valid export file format."
        sys.exit(1)

    # verify given path is accesible file
    if not os.path.isfile(args.import_file):
        print >> sys.stderr, "Given path is not a file: %s" % args.import_file
        sys.exit(1)

    # read from formated fixed-width file
    data = import_data(args.import_file)

    # export data to specified format
    # to make this Unix-lixe pipe-able
    # we just print to stdout
    print write_data(data, args.export_format)

Data_r_and_w(csv,json,xlsx)的更多相关文章

  1. csv与xlsx导出

    一.csv与xlsx格式基本介绍       csv即comma seperate values - 逗号分隔值,文件以纯文本形式来存储表格数据,它可以由任意数目的记录组成,记录之间通过某种换行符来分 ...

  2. Python json数据写入csv json excel文件

    一.写入 写入csv和json, 可以使用csv这个包写, 我这里没有使用, 并且把写csv和json的写到一起了 具体的代码就不解释了 def write_file(file_name, items ...

  3. csv/json/list/datatable导出为excel的通用模块设计

    导出excel的场景我一般都是一个List直接导出成一张sheet,用Npoi.Mapper库很方便,最近我经常是需要将接口返回的jsonarray转成一张excel表,比如从elasticsearc ...

  4. CSV to XLSX (专用)

    $csvFile = "F:\ACL\HZ ACL\ACL-APAC.CSV" $path = "F:\ACL\HZ ACL\ACL-APAC.XLSX" $r ...

  5. txt,csv,json互相转化

    也没啥,记下来怕忘了.说明都在代码里面: 麻蛋,这个着色好难看 import csv import json #从txt变为csv student_txt=[]; with open("st ...

  6. csv,json格式数据的读写

    #!python3 # -*- coding:utf-8 -*- #CSV stands for "comma-separated values",and CSV files ar ...

  7. solr curl索引 CSV/Json/xml文件

    在windows系统中,用curl命令工具索引文件命令: 启动solr 在solr-6.6.0\bin的同级目录下的文件夹ImportData下要索引的文件. 1.索引 json文件 curl &qu ...

  8. python cookbook第三版学习笔记七:python解析csv,json,xml文件

    CSV文件读取: Csv文件格式如下:分别有2行三列. 访问代码如下: f=open(r'E:\py_prj\test.csv','rb') f_csv=csv.reader(f) for f in ...

  9. spark 读写text,csv,json,parquet

    以下代码演示的是spark读取 text,csv,json,parquet格式的file 为dataframe, 将dataframe保存为对应格式的文件 package com.jason.spar ...

随机推荐

  1. Python学习笔记 - 迭代Iteration

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- d = {'a': 1, 'b': 2, 'c': 3} for key in d: # 默认迭代是key ...

  2. 移植Cocos2D到Android平台的原理

    幸运的,SpriteBuilder使得适配(安卓)多种多样的屏幕尺寸变得容易起来,因为Android Xcode插件允许你使用任何Cocos2D的特性并且可以继续使用很多iOS的框架(framewor ...

  3. Android For JNI(五)——C语言多级指针,结构体,联合体,枚举,自定义类型

    Android For JNI(五)--C语言多级指针,结构体,联合体,枚举,自定义类型 我们的C已经渐渐的步入正轨了,基础过去之后,就是我们的NDK和JNI实战了 一.多级指针 指针的概念我们在前面 ...

  4. Gradle 1.12用户指南翻译——第二十三章. Java 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

  5. Android 之dragger使用

    1.依赖的注入和配置独立于组件之外,注入的对象在一个独立.不耦合的地方初始化,这样在改变注入对象时,我们只需要修改对象的实现方法,而不用大改代码库. 2.依赖可以注入到一个组件中:我们可以注入这些依赖 ...

  6. 如何解决Asp.Net中不能上传压缩文件的问题

    在使用Asp.Net自带的服务器端控件Fileupload上传文件时,可能会出现不能上传压缩文件的问题,此时可以通过下面的方法解决: 在<system.web>中添加: <httpR ...

  7. C语言实现快速翻转数组的顺序

    #include <stdio.h> void Reverse(int *p , int size) { int i , tmp; for(i = 0 ; i < size/2 ; ...

  8. 如何使用ZOL一键安装器下载中关村在线的源安装包

    如何使用ZOL一键安装器下载中关村在线的源安装包 马根峰               (广东联合电子服务股份有限公司, 广州 510300) 摘要    中关村在线最近开始推出ZOL一键安装器,用户直 ...

  9. vicoapp使用备忘

    vico是一个模式编辑器,意味着没用过vi之类编辑器的童鞋用起来肯定觉得很不习惯. 模式切换 i:切至编辑模式,在光标前插入 a:切至编辑模式,在在光标后插入 I:类似于i,不过在行首插入 esc键: ...

  10. apt-get Ubuntu本地ISO镜像入源

    转自http://blog.csdn.net/binchel/article/details/21486999 在没有网络的情况下,本地镜像源不实为一个上等的权宜之计! 目前linux的两大主流包管理 ...