[英]Combining two csv files together in perl
Hi i'm very new to perl and i've got litle knowledge on it but i'm trying to create a script that conbines two .csv files into a new one 嗨,我是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 ($!)";
}
this is my current code i do know this over write's the data insted of actually adding it to the new file but this is how far i managed to get with the limited time and knowledge i've got on perl 这是我当前的代码,我确实知道这是重写,实际上是将数据添加到新文件中的数据,但这是我在有限的时间和知识基础上设法达到的程度
the csv format of both files are the same. 两个文件的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"
I believe the issue is here: 我相信问题在这里:
open my $fh, '>', $file
or die "Cannot open $file ($!)";
If I remember my Perl properly, the line should read: 如果我正确记得我的Perl,则该行应显示为:
open my $fh, '>>', $file
or die "Cannot open $file ($!)";
The >>
should open the file handle $fh
for append instead of for overwrite. >>
应该打开文件句柄$fh
进行追加,而不是覆盖。
you could try something like this 你可以尝试这样的事情
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);
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.