【问题标题】:Write to new CSV file写入新的 CSV 文件
【发布时间】:2018-08-01 14:20:23
【问题描述】:

我正在尝试将数据写入新的 CSV 文件。我知道如何创建新文件以及如何从旧文件中收集我想要的数据,但我不确定如何将收集到的数据实际写入新文件。我希望我打印的列也写入新的 CSV 文件。这是我目前所拥有的:

use strict;
use warnings;

use Text::CSV_XS;

my @data;
my $file = 'FinalTest.csv'; #original file
my $newfile = 'filteredData.csv'; #new file

my $csv = Text::CSV_XS->new({ binary => 1 });
open my $fh, '<', $file or die "Could not open $file: $!";

my $header = $csv->getline($fh)
   or die("No header\n");
$csv->column_names(@$header); #removes header row

while( my $row = $csv->getline($fh) ) {
    push @data, $row;
    printf "$row->[0]\t";
    printf "$row->[1]\t";
    printf "$row->[2]\t";
    printf "$row->[3]\t";
    printf "$row->[13]\n";
}

open my $newfile, '>', $newfile or die "Could not write $newfile"; #create new file

【问题讨论】:

  • 为什么不干脆做:./script.pl &gt; new_file.csv
  • this post中写入CSV的完整简单示例

标签: perl file csv text


【解决方案1】:

你已经很接近了,你只是把事情弄错了。 open 新文件的行应该在 while 循环之前。然后您需要将该文件句柄添加到printf 语句中。尽管实际上它们应该只是 print 语句,因为您没有进行任何格式化。

open my $newfile, '>', $newfile or die "Could not write $newfile"; #create new file

while( my $row = $csv->getline($fh) ) {
    push @data, $row;
    print $newfile "$row->[0]\t";
    print $newfile "$row->[1]\t";
    print $newfile "$row->[2]\t";
    print $newfile "$row->[3]\t";
    print $newfile "$row->[13]\n";
}

此外,您还可以像这样执行输出的行,因为如果您想更改要输出的列或重新排序它们,它会更容易。

print $newfile join("\t",@$row[0,1,2,3,13]),"\n";

如果您需要输出中的标头,请将其放在循环之前。

print $newfile join("\t",@$header[0,1,2,3,13]),"\n";

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 2014-05-10
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多