Skip to content

Instantly share code, notes, and snippets.

@welch
Last active August 27, 2015 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save welch/92e1a9cba4af229fb520 to your computer and use it in GitHub Desktop.
Save welch/92e1a9cba4af229fb520 to your computer and use it in GitHub Desktop.
convert zemax pupil data to csv
#!/usr/bin/env python
"""
zmx2csv.py: convert zemax output to csv for matlab import
usage: zmx2csv.py filename.txt ...
reads each filename.txt, outputting filename.csv
sample input file: forPupilMapping_Prescription.txt
"""
import sys
import argparse
import csv
def parse_line(line):
name, value = line.split(':')
name = name.strip()
value = value.split("=")[-1].split(",")[-1].split("(")[0].strip()
# pull a number out of the value string if we can
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
pass
return name, value
def main(args=None, skip=10, keep=50):
parser = argparse.ArgumentParser(
description='Infer log message patterns from logfiles'
)
parser.add_argument(
"infile", nargs='*',
help="path(s) to input files.")
parser.add_argument(
"--skip", type=int, default=skip,
help="skip this many lines at the beginning (default = %d)" % skip)
parser.add_argument(
"--keep", type=int, default=keep,
help="keep this many lines after skipping (default = %d)" % keep)
parser.add_argument(
"--all", action='store_true',
help="keep lines without numeric data")
parser.add_argument(
"--noheader", action='store_true',
help="don't write header in csv file")
args = parser.parse_args(args=args)
for fname in args.infile:
data = {}
with open(fname,"r") as f:
for i, line in enumerate(f):
line = line.replace('\0', '').replace('\r','') # remove DOS bullshit
if (i < args.skip):
continue
elif (i == args.skip + args.keep):
break
name, value = parse_line(line)
if (args.all or isinstance(value, (int, float))):
data[name] = value
# data now contains an entry for each keeper line
fname_csv = fname.split('.')[0]+'.csv'
with open(fname_csv, 'w') as csvfile:
writer = csv.DictWriter(csvfile, data.keys())
if (not args.noheader):
writer.writeheader()
writer.writerow(data)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment