import os,Nio
import numpy as np

os.system("rm -f stringtest.nc")
ncfile = Nio.open_file('stringtest.nc', 'w')

ncfile.create_dimension('strlen', 30)
ncfile.create_dimension('strcnt', 3)

strings = ['this is a string','this is a longer string', 'this is an even longer string']
scalarstrvar = ncfile.create_variable('scalarstrvar', 'S1', ())
strvar = ncfile.create_variable('strvar', 'S1', ('strlen',))
strvar1 = ncfile.create_variable('strvar1', 'S1', ('strcnt','strlen',))

scalarstrvar.assign_value('x')
# character arrays in PyNIO must be set with the expected number of characters
# since by default NetCDF prefills character arrays with 0 (the NULL byte)
# the simple approach is to subscript the file variable using the string length

# 1D variable
strvar[:len(strings[0])] = strings[0]

# 2D variable with varying length strings
count = 0
for str in strings:
    strvar1[count,:len(str)] = str
    count += 1

ncfile.close()

