Convert fixed-width file to CSV
Posted by Kelvin on 12 May 2011 at 07:11 am | Tagged as: programming, Ubuntu
After trying various sed/awk recipes to convert from fixed-width to CSV, I found a Python script that works well.
Here it is, from http://code.activestate.com/recipes/452503-convert-db-fixed-width-output-to-csv-format/
## {{{ http://code.activestate.com/recipes/452503/ (r1) # Ian Maurer # http://itmaurer.com/ # Convert a Fixed Width file to a CSV with Headers # # Requires following format: # # header1 header2 header3 # ------------ ------- ---------------- # data_a1 data_a2 data_a3 def writerow(ofile, row): for i in range(len(row)): row[i] = '"' + row[i].replace('"', '') + '"' data = ",".join(row) ofile.write(data) ofile.write("\n") def convert(ifile, ofile): header = ifile.readline().strip() while not header: header = ifile.readline().strip() hticks = ifile.readline().strip() csizes = [len(cticks) for cticks in hticks.split()] line = header while line: start, row = 0, [] for csize in csizes: column = line[start:start+csize].strip() row.append(column) start = start + csize + 1 writerow(ofile, row) line = ifile.readline().strip() if __name__ == "__main__": import sys if len(sys.argv) == 3: ifile = open(sys.argv[1], "r") ofile = open(sys.argv[2], "w+") convert(ifile, ofile) else: print "Usage: python convert.py <input> <output>" ## end of http://code.activestate.com/recipes/452503/ }}}
- Introducing Bash-whacking
- Recursively delete .svn folders
- Move up multiple directories in bash
- Download youtube videos as mp3
- Useful ffmpeg commands
- Recursively copy only files with certain extension with rsync
- Recursive directory listing sorted by file size
- Download google video and youtube from command-line
- Reset wireless in Ubuntu 10.04 Lucid
- Delete files older than x days
- MD5 a directory recursively
- Convert fixed-width file to CSV
- Recursively find the n latest modified files in a directory
- Using sed to delete lines from a file
- Determine if a server supports Gzip compression
- Delete directories older than x days
- Mount a .dmg file in Ubuntu
- Batch convert svg to png in Ubuntu
- Split wav/flac/ape files with cue