Data_r_and_w(csv,json,xlsx)
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)的更多相关文章
- csv与xlsx导出
一.csv与xlsx格式基本介绍 csv即comma seperate values - 逗号分隔值,文件以纯文本形式来存储表格数据,它可以由任意数目的记录组成,记录之间通过某种换行符来分 ...
- Python json数据写入csv json excel文件
一.写入 写入csv和json, 可以使用csv这个包写, 我这里没有使用, 并且把写csv和json的写到一起了 具体的代码就不解释了 def write_file(file_name, items ...
- csv/json/list/datatable导出为excel的通用模块设计
导出excel的场景我一般都是一个List直接导出成一张sheet,用Npoi.Mapper库很方便,最近我经常是需要将接口返回的jsonarray转成一张excel表,比如从elasticsearc ...
- CSV to XLSX (专用)
$csvFile = "F:\ACL\HZ ACL\ACL-APAC.CSV" $path = "F:\ACL\HZ ACL\ACL-APAC.XLSX" $r ...
- txt,csv,json互相转化
也没啥,记下来怕忘了.说明都在代码里面: 麻蛋,这个着色好难看 import csv import json #从txt变为csv student_txt=[]; with open("st ...
- csv,json格式数据的读写
#!python3 # -*- coding:utf-8 -*- #CSV stands for "comma-separated values",and CSV files ar ...
- solr curl索引 CSV/Json/xml文件
在windows系统中,用curl命令工具索引文件命令: 启动solr 在solr-6.6.0\bin的同级目录下的文件夹ImportData下要索引的文件. 1.索引 json文件 curl &qu ...
- 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 ...
- spark 读写text,csv,json,parquet
以下代码演示的是spark读取 text,csv,json,parquet格式的file 为dataframe, 将dataframe保存为对应格式的文件 package com.jason.spar ...
随机推荐
- 最新的App上架教程Object-C
准备 开发者账号 完工的项目 上架步骤 一.创建App ID 二.创建证书请求文件 (CSR文件) 三.创建发布证书 (CER) 四.创建Provisioning Profiles配置文件 (PP文件 ...
- 【一天一道LeetCode】#45. Jump Game II
一天一道LeetCode系列 (一)题目 Given an array of non-negative integers, you are initially positioned at the fi ...
- vim的颜色修改,高亮设置。
在vim.org 搜一下,下载一个color scheme, 放到~/.vim/colors/下(linux)或者$HOME/.vim/colors/下(windows) 再在你的.vimrc文件中加 ...
- 更新Cocos2D支持Xcode 7
原文链接(有节选简写) Apple已经释放出Xcode7,给我们带来了Swift2和每个平台的最新版本支持.Cocos2D却还在等待更新去兼容Apple的改变.不幸的是,SpriteBuilder还未 ...
- Oracle EBS 重新编译无效对象 invalid object
1. 查看数据库中的无效对象 check oracle object SQL> select count(*) from dba_objects where status= ...
- Using Integrated SOA Gateway in Oracle EBS
FROM:http://blog.csdn.net/pan_tian/article/details/10159935 Oracle EBS如何与第三方系统相集成?比如这样的需求,X系统知道物料编码, ...
- LeetCode之“链表”:Reorder List
题目链接 题目要求: Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You ...
- 虚拟机linux挂载光盘显示:mount: you must specify the filesystem type
虚拟机内 linux 挂载光盘显示:mount: you must specify the filesystem type 今天在虚拟机上挂载镜像文件时提示: 初步断定原因有2: 1.在卸载光盘时使用 ...
- unity C#更改系统默认鼠标指针
最近项目需要替换鼠标的默认图标,实现的效果是初始状态为一种图标,点击鼠标左键要换成另一种图标,按网上通用的方法做了以后,隐藏鼠标指针,在指针的位置画一个图片就可以了,但不知道怎么回事,这种方法画的图标 ...
- 如何在os x或ubuntu下安装最新的ruby
os x下基本上可以安装到比较新的ruby,首先先安装rvm,然后用rvm list known看当前可供安装的ruby的版本,不过这也不是绝对的,比如在我的os x 10.9上,命令返回如下: # ...