Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read CSV file and save in 2 d array

Tags:

arrays

perl

I am trying to read a huge CSV file in 2 D array, there must be a better way to split the line and save it in the 2 D array in one step :s Cheers

my $j = 0;
while (<IN>) 
{

    chomp ;
    my @cols=();
    @cols   = split(/,/); 
    shift(@cols) ; #to remove the first number which is a line header
    for(my $i=0; $i<11; $i++) 
    {
       $array[$i][$j]  = $cols[$i];
    }        
    $j++;    
}
like image 874
user1014843 Avatar asked Oct 26 '11 15:10

user1014843


People also ask

How do I save an array of values as a CSV file?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

How do I convert a CSV file to a 2D list in Python?

Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to np. loadtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.


2 Answers

CSV is not trivial. Don't parse it yourself. Use a module like Text::CSV, which will do it correctly and fast.

use strict;
use warnings;

use Text::CSV;

my @data;   # 2D array for CSV data
my $file = 'something.csv';

my $csv = Text::CSV->new;
open my $fh, '<', $file or die "Could not open $file: $!";

while( my $row = $csv->getline( $fh ) ) { 
    shift @$row;        # throw away first value
    push @data, $row;
}

That will get all your rows nicely in @data, without worrying about parsing CSV yourself.

like image 90
friedo Avatar answered Sep 28 '22 08:09

friedo


If you ever find yourself reaching for the C-style for loop, then there's a good chance that your program design can be improved.

while (<IN>) {
    chomp;

    my @cols = split(/,/); 
    shift(@cols); #to remove the first number which is a line header

    push @array, \@cols;
}

This assumes that you have a CSV file that can be processed with a simple split (i.e. the records contain no embedded commas).

like image 45
Dave Cross Avatar answered Sep 28 '22 09:09

Dave Cross