Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {
- "collapsed": true
- },
- "outputs": [],
- "source": [
- "import csv\n",
- "import json\n",
- "\n",
- "classes = {'0':'car', '1':'bike'}\n",
- "\n",
- "final_output = [\n",
- " [\n",
- " 'filename1',\n",
- " 250,\n",
- " {'class': classes['0'], 'attr':['a', 'b', 'c']},\n",
- " ['hello', 'man'],\n",
- " 5\n",
- " ],\n",
- " [\n",
- " 'filename2',\n",
- " 355,\n",
- " {'class': classes['1'], 'attr':['c', 'd', 'a']},\n",
- " ['howdy', 'man'],\n",
- " 10\n",
- " ]\n",
- "]\n",
- "y = ['filename', 'file_size', 'file_attributes', 'some_array', 'region_count']\n",
- "\n",
- "with open('file.csv', 'w', newline='') as f:\n",
- " wr = csv.writer(f, delimiter=';')\n",
- " wr.writerow(y)\n",
- " for output in final_output:\n",
- " jsonified_output = [json.dumps(o) if isinstance(o, dict) or isinstance(o, list) else o for o in output]\n",
- " wr.writerow(jsonified_output)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## csv file's content would look like this\n",
- "\n",
- "```\n",
- "filename;file_size;file_attributes;some_array;region_count\n",
- "filename1;250;\"{\"\"class\"\": \"\"car\"\", \"\"attr\"\": [\"\"a\"\", \"\"b\"\", \"\"c\"\"]}\";\"[\"\"hello\"\", \"\"man\"\"]\";5\n",
- "filename2;355;\"{\"\"class\"\": \"\"bike\"\", \"\"attr\"\": [\"\"c\"\", \"\"d\"\", \"\"a\"\"]}\";\"[\"\"howdy\"\", \"\"man\"\"]\";10\n",
- "```"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "car\n",
- "hello\n",
- "bike\n",
- "howdy\n"
- ]
- }
- ],
- "source": [
- "with open('file.csv', 'r') as csv_file:\n",
- " rd = csv.reader(csv_file, delimiter=';')\n",
- " next(rd, None) # skip the header row\n",
- " for row in rd:\n",
- " file_attributes = row[2]\n",
- " fileattr_dict = json.loads(file_attributes)\n",
- " print(fileattr_dict['class'])\n",
- " arr = row[3]\n",
- " arr_list = json.loads(arr)\n",
- " print(arr_list[0])\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.6.1"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement