It's a hassle to manually create a CSV container class Create a C # container class by automatically parsing CSV types etc. I tried to create a generator. Please note that the CSV format has simple rules.
By the way, Python is just beginning to study There may be something wrong with the code. In that case, it would be very helpful if you could point it out.
I feel like this.
test_csv.csv
id,key1,key2,key3
1,Test 1,1.0,1,
2,Test 2,2.0,2,
3,Test 3,3.0,3,
The top line is the name of the key. This will be the variable name. After that, please enter the contents of csv data from the second line.
CSVContainerTestCsv.cs
using System.Collections;
using System.Collections.Generic;
namespace CSVContainer
{
//Real container data
public class TestCsv
{
public int id{ get; private set;}
public string key1{ get; private set;}
public float key2{ get; private set;}
public int key3{ get; private set;}
}
}
I feel like this. It is enclosed in namespace because it is convenient in various ways.
The class name is a camel case of the CSV file name. The .cs name is "CSVContainer" + class name.
CSVContainerGenerator.py
# -*- coding: utf-8 -*-
import glob
import os.path
def convert(file):
count = 0
culam = ""
val = ""
for line in open(file, 'r'):
if count == 0:
culam = line
count += 1
else:
val = line
break
out_put(file, culam, val)
def out_put(file, culam, val):
file_name = os.path.basename(file)
base_name = file_name.replace(".csv","")
cs_name = "CSVContainer" + to_camel_case(base_name) + ".cs"
f = create_file(cs_name, base_name)
create_class(culam, val, f, to_camel_case(base_name))
# print file_name
def create_file(file, base_name):
f = open(file, 'w')
f.write("using System.Collections;\n")
f.write("using System.Collections.Generic;\n")
f.write("\n")
f.write("namespace CSVContainer\n")
f.write("{\n")
f.write("\t//Real container data\n")
f.write("\tpublic class "+to_camel_case(base_name)+"\n")
return f
def create_class(culam, val, f, base_name):
f.write("\t{\n")
culams = culam.split(",")
vals = val.split(",")
for i, v in enumerate(culams):
type_str = ""
if vals[i].find('.') != -1:
type_str = "float\t"
elif vals[i].isdigit():
type_str = "int\t\t"
else :
type_str = "string\t"
v = v.replace("\n", "")
v = v.replace("¥n", "")
f.write("\t\tpublic " + type_str + " " + v + "{ get; private set;}\n")
f.write("\t}\n")
f.write("\n")
f.write("}\n")
def to_camel_case(text):
text = text.lower()
text = text.capitalize()
while '_' in text:
ix = text.index('_')
next = text[ix + 1].upper()
text = text[0:ix] + next + text[ix + 2:]
return text
for file in glob.glob('CSV/*.csv'):
print "conv " , file
convert(file)
Currently, I go to see the CSV in the CSV directory. The output destination is the same layer as the py code. I hope you can play around with this area. To be honest, it's lazy to make a directory a direct value.
that's all