Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.

Convert a CSV into a Plist file

Here’s some code from awhile back. It’ll take a CSV and turn it into a Plist file.

The structure works like this:

The first row of your CSV is considered to be the header. The code will use content from the header row to create key names. For every subsequent row, the code will create a dictionary, associating the content of each column with the key names from the header. The dictionaries live in an array which is written out to a Plist file.

This is handy if you’ve got a bunch of spreadsheet-type data you’d like to use as the basis for a static reference in your app. Say, data about the periodic table, airport listings, trivia questions, whatever. You can sift and sort your data in a user-friendly environment like Numbers or Excel, then dump it out to CSV and put this code to work.

It uses cCSVParse to read the CSV file.

//	NSLog(@"Converting %@",pathAsString);
	CSVParser *parser = [CSVParser new];
	[parser openFileWithPath:pathAsString];
	NSMutableArray *csvContent = [parser parseFile];
	[parser closeFile];
	if (pathAsString != nil)
		NSArray *keyArray = [csvContent objectAtIndex:0];
		NSMutableArray *plistOutputArray = [NSMutableArray array];
		NSInteger i = 0;
		for (NSArray *array in csvContent)
			NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
			NSInteger keyNumber = 0;
			for (NSString *string in array)
				[dictionary setObject:string forKey:[keyArray objectAtIndex:keyNumber]];
			if (i > 0)
				[plistOutputArray addObject:dictionary];
//		NSLog(@"Plist output array %@", plistOutputArray);
		NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString];
		[mutableString replaceOccurrencesOfString:@".csv" withString:@".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)];
		NSURL *url = [NSURL fileURLWithPath:mutableString];
//		NSLog(@"Write to URL %@",url);
		[plistOutputArray writeToURL:url atomically:YES];

That’s from a simple desktop app I built for the purpose. It takes the path of your CSV, via drag-and-drop, then spits out the Plist beside it.  You can grab the source at Google Code. You can also download this compiled binary if you want to get crackin’ right away.

  • Thanks! That’s really useful! :)


    January 3, 2010

  • It doesn’t process UTF-8 files correctly.



    March 14, 2010

  • Hey,

    Thanks a lot this is what i am searching for


    April 19, 2010

  • Wow…perfect. This just saved me a ton of time. Thanks much! Worked like a champ the 1st time.


    October 15, 2010

  • Thanks a lot ! Here is a Quartz Composer plugin I made from your CSV parser :

    Benoît Lahoz

    June 6, 2011

  • Thanks very much mate, nifty little tool :D


    June 14, 2011

Leave a comment  




Submit comment