嗨,我对perl非常陌生,而且我对它有一些知识,但我正在尝试创建一个将两个.csv文件合并为一个新文件的脚本
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV_XS;
my @rows;
{ # Read the CSV file
my $csv = Text::CSV_XS->new() or die "Cannot use Text::CSV_XS ($!)";
my $file = "file.csv";
open my $fh, '<', $file or die "Cannot open $file ($!)";
while (my $row = $csv->getline($fh)) {
push @rows, $row;
}
$csv->eof or $csv->error_diag();
close $fh or die "Failed to close $file ($!)";
}
{ # Gather the data
foreach my $row (@rows) {
foreach my $col (@{$row}) {
$col = uc($col);
}
print "\n";
}
}
# (over)Write the data
# Needs to be changed to ADD data
{
my $csv = Text::CSV_XS->new({ binary => 1, escape_char => undef })
or die "Cannot use Text::CSV ($!)";
my $file = "output.csv";
open my $fh, '>', $file or die "Cannot open $file ($!)";
$csv->eol("\n");
foreach my $row (@rows) {
$csv->print($fh, \@{$row}) or die "Failed to write $file ($!)";
}
close $fh or die "Failed to close $file ($!)";
}
这是我目前的代码,我知道这是写的,实际将其添加到新文件中的数据,但这是我在perl上获得的有限时间和知识所能达到的程度
两个文件的csv格式相同。
"Header1";"Header2";"Header3";"Header4";"Header5"
"Data1";"Data2";"Data3";"Data4";"Data5"
"Data1";"Data2";"Data3";"Data4";"Data5"
"Data1";"Data2";"Data3";"Data4";"Data5"
"Data1";"Data2";"Data3";"Data4";"Data5"
"Data1";"Data2";"Data3";"Data4";"Data5"
答案 0 :(得分:0)
我相信问题在这里:
open my $fh, '>', $file
or die "Cannot open $file ($!)";
如果我记得我的Perl正确,该行应为:
open my $fh, '>>', $file
or die "Cannot open $file ($!)";
>>
应该打开文件句柄$fh
以进行追加而不是覆盖。
答案 1 :(得分:0)
你可以尝试这样的事情
opendir(hand,"DIRPATH");
@files = readdir(hand);
closedir(hand);
foreach(@files){
if(/\.csv$/i) { #if the filename has .csv at the end
push(@csvfiles,$_);
}
}
foreach(@csvfiles) {
$csvfile=$_;
open(hanr,"DIRPATH".$csvfile)or die"error $!\n"; #read handler
open(hanw , ">>DIRPATH"."outputfile.csv") or die"error $! \n"; #write handler for creating new sorted files
@lines=();
@lines=<hanr>;
foreach $line (@lines){
chomp $line;
$count++;
next unless $count; # skip header i.e the first line containing stock details
print hanw join $line,"\n";
}
$count= -1;
close(hanw);
close(hanr);
}`