Convert CSV file to directories


A fellow co-worker had a need to turn a CSV file into a series of directories and files where the columns of the CSV file were the directories, and the contents of the cells for each row were made into a text file and placed in the appropriate folder corresponding to the column. For example given the CSV file with the columns (name,email,number,date), and several rows like this:

john,j@j.com,89,tuesday

bertha,b@j.com,2716,monday

dillan,d@j.com,289,saturday

xavier,x@j.com,839,wednesday

The script would create four numbered folders (1, 2, 3, 4), and put a file in each folder corresponding with the row number and column.

Columns into folders, cells into text files

So, within folder number one would be four text files named 1-1.txt, 2-1.txt, 3-1.txt, 4-1.txt. Text file 1-1.txt would contain the content “john”. File 3-1.txt would contain the text “dillan”. Within folder number 3 would be four text files named 1-3.txt, 2-3.txt, 3-3.txt, and 4-3.txt.

Well, anyhow, I hope that explanation makes sense. Here’s the code:

[code lang=”perl”]
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV::Encoded;

my $csv = Text::CSV::Encoded->new();

# file to be used given on the command line as an argument to the script
open (CSV, “<:encoding(UTF-8)”, $ARGV[0]) or die $!;

my $rownum = 1;
while () {
if ($csv->parse($_)) {
# Put the rows into an array
my @columns = $csv->fields();

# Make the directories, as many as there are columns
# Get the number of columns (which is the number of elements in the
# array).
my $size = scalar(@columns);
my $count = 1;
# Check if the directories are created. Only want to make them on the
# interration through the first row
if ( !-d $count ) {
while ($count <= $size) { mkdir “$count” or die $!; $count++; } } # Now make a file from each cell, putting the file in the directory # corresponding to the column my $colnum = 1; for my $column (@columns) { # Create a new file (or overwrite an existing one) in the # appropriate column folder and name it row#-col#.txt open FILE, “+>$colnum/row$rownum-col$colnum.txt” or die $!;
# This sets the correct encoding on writing to the file
binmode FILE, “:utf8”;
print FILE $column;
close FILE;
$colnum++;
}

} else {
my $err = $csv->error_input;
print “Failed to parse line: $err”;
}

$rownum++;
}
close CSV;

[/code]

Share and Enjoy:
  • Print
  • PDF
  • RSS

Related Posts:

  • No Related Posts