use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new({ binary => 1 }) or die;
open(my $fh, ">", "test.csv") or die;
if (1) { # header
$csv->combine(("id", "data", "name"));
print($fh $csv->string() . "\n");
}
$csv->combine((1, 1.1, "record 1")); print($fh $csv->string() . "\n");
$csv->combine((2, 2.2, "record 2")); print($fh $csv->string() . "\n");
$csv->combine((3, 3.3, "record 3")); print($fh $csv->string() . "\n");
close($fh);
|
import csv
with open('test.csv', 'w') as f:
writer = csv.writer(f)
if True: # header
writer.writerow(['id', 'data', 'name'])
writer.writerow([1, 1.1, 'record 1'])
writer.writerow([2, 2.2, 'record 2'])
writer.writerow([3, 3.3, 'record 3'])
|
use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new({ binary => 1 }) or die;
open(my $fh, "<", "test.csv") or die;
if (1) {
$csv->parse(scalar <$fh>) or die;
my @header = $csv->fields();
print("@header\n");
}
while (<$fh>) {
$csv->parse($_) or die;
my @row = $csv->fields();
print("@row\n");
}
close($fh);
|
import csv
with open('test.csv') as f:
reader = csv.reader(f)
if True:
header = next(reader)
assert type(header) == list
print(header)
for row in reader:
assert type(row) == list
print(row)
|
import csv
with open('test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
assert type(row) == dict
print(row['id'], row['data'], row['name'])
|