【问题标题】:How to read a csv using Perl?如何使用 Perl 读取 csv?
【发布时间】:2021-01-02 02:14:33
【问题描述】:

我想使用 perl 读取 csv,不包括第一行。此外,col 2 和 col3 变量需要存储在另一个文件中,并且必须删除读取的行。

编辑:以下代码有效。我只想要删除部分。

use strict;
use warnings;

my ($field1, $field2, $field3, $line);
my $file = 'D:\Patching_test\ptch_file.csv';

open( my $data, '<', $file ) or die;
while ( $line = <$data> ) {
    next if $. == 1;
    ( $field1, $field2, $field3 ) = split ',', $line;
    print "$field1 : $field2 : $field3 ";

    my $filename = 'D:\DB_Patch.properties';
    unlink $filename;

    open( my $sh, '>', $filename )
      or die "Could not open file '$filename' $!";

    print $sh "Patch_id=$field2\n";
    print $sh "Patch_Name=$field3";
    close($sh);

    close($data);
    exit 0;
}

【问题讨论】:

  • 通过使用Text::CSV_XS Perl 模块,您可以读取CSV 文件并进行操作。请向我们展示您的代码,这将有助于人们回答您的问题。
  • 已编辑代码。
  • 必须删除行读取 - 这是什么意思?
  • 我在属性文件中写的行必须从csv中删除
  • @Shivani 我建议您在$filename 上执行的任何操作都应在while 循环之外完成,除了使用$sh 文件处理程序打印内容。

标签: csv perl


【解决方案1】:

OPs 问题处理不当

  • 未提供输入数据样本
  • 没有提供所需的输出数据
  • 处理后未修改输入文件

基于以下提供的代码的问题描述

use strict;
use warnings;
use feature 'say';

my $input   = 'D:\Patching_test\ptch_file.csv';
my $output  = 'D:\DB_Patch.properties';
my $temp    = 'D:\script_temp.dat';

open my $in, '<', $input
    or die "Couldn't open $input";

open my $out, '>', $output
    or die "Couldn't open $output";

open my $tmp, '>', $temp
    or die "Couldn't open $temp";
    
while ( <$in> ) {
    if( $. == 1 ) {
        say $tmp $_;
    } else {
        my($patch_id, $patch_name) = (split ',')[1,2];
        say $out "Patch_id=$patch_id";
        say $out "Patch_Name=$patch_name";
    }
}

close $in;
close $out;
close $tmp;

rename $temp,$input;

exit 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-01
    • 2014-05-09
    • 1970-01-01
    • 2017-08-31
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多