Skip to content

Instantly share code, notes, and snippets.

@xeBuz
Created February 5, 2015 20:45
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 xeBuz/8df66899f7ac17d4bc4e to your computer and use it in GitHub Desktop.
Save xeBuz/8df66899f7ac17d4bc4e to your computer and use it in GitHub Desktop.
Convert a CSV to a PHP key-value fields
import csv
import os
import argparse
parser = argparse.ArgumentParser(description='Convert CSV Columns to a PHP KeyValue array')
parser.add_argument('-f', '--file', action='store', dest='file', default='exampe.csv', help="CSV file. Default: exmple.csv")
parser.add_argument('-k', '--key', action='store', dest='column_key', default='0', help="Key Column Number")
parser.add_argument('-v', '--value', action='store', dest='column_value', default='1', help="Value Column Number")
args = parser.parse_args()
def main():
csvfile = args.file
key = int(args.column_key)
value = int(args.column_value)
if not os.path.isfile(csvfile):
exit('Invalid file')
with open(csvfile, 'rb') as f:
reader = csv.reader(f)
for row in reader:
print "'"+row[key]+"' => '"+row[value]+"',"
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment