【问题标题】:how to add one value in file output如何在文件输出中添加一个值
【发布时间】:2017-02-13 21:40:46
【问题描述】:

我的要求是读取一个文件并在每行末尾添加一个值。谁能告诉我该怎么做?

这是我的代码:

open( OFILE, "<$source_path" ) or die "could not open file";

while ( <OFILE> ) {

    my @iline = ( $_ );

    #print "@iline\n";
    #print "$iline[0]\n";
    #print "$iline[1]\n";
    #push @iline, '4';
    #print "@iline \n";

    open( IFILE, ">$target_directory_pacss" );

    {
        foreach ( @iline ) {

            #print IFILE "$_[0]".","."$_[1]".","."$_[2]" ;
            #print  "$_[0]".","."$_[1]".","."$ival" ;
            #print "\n";

            print IFILE "$_";
            print "\n";
        }
    }

    close( IFILE );
}

我到底想要多少

输入

patie,1234
patie,1235
patie,1236

输出

patie,1234,4
patie,1235,4
patie,1236,4

【问题讨论】:

  • 好吧,除了有点奇怪的语法——我们需要知道你所说的“在每一行添加一个值”是什么意思——因为你的代码没有。因此,一些示例输入和预期输出可能会有所帮助。
  • 好的。那么 - '4' 是从哪里来的呢?是静态值吗?还是动态的?
  • sed -e 's/$/,4/'

标签: perl


【解决方案1】:

下面提到的代码是实现所需输出的最简单方法。 我假设您只需要在每一行的末尾附加一些内容即可将其保存为新文件。因此,根据您所需的输出,我在每行之后附加了“,4”。

此代码逐行读取源文件,并使用所需的修改值写入新文件。

my $source_path = "file.txt";
my $target_directory_pacss = "file2.txt";

open(OFILE, "<$source_path") or die "could not open file";
open(IFILE, ">$target_directory_pacss");

while(<OFILE>) {
    chomp;
    print IFILE $_.",4\n";
}
close( OFILE);
close( IFILE );

使用 chomp :因为在添加任何值之前,您需要去掉每行末尾的换行符。

输出:

patie,1234,4
patie,1235,4
patie,1236,4

【讨论】:

    【解决方案2】:

    您可以按照下面的代码工作。您可以先读取数组中的整个文件,然后使用附加的行将其记录到另一个文件中。

    my $source_path = "source.txt";
    my $target_directory_pacss = "destination.txt";
    
    open(OFILE,"<$source_path") or die "could not open file";
    chomp(my @lines = <OFILE>);
    close(OFILE);
    
    open(IFILE,">$target_directory_pacss");
    
    foreach my $line(@lines){
        print IFILE "$line"."EOL"."\n";
    }
    close(OFILE);
    close (IFILE);
    

    我在上面代码的每一行末尾都附加了字符串“EOL”。

    【讨论】:

    • 但是说真的,当while 循环做得非常好时,你为什么要foreach。并且请使用带有词法文件句柄的 3-arg open。这是更好的风格。
    • “你可以先读取数组中的整个文件” 为什么要这样做?
    • 这种将文件读入数组的方法在我们处理多个文件的情况下非常有用,因为 I/O 操作需要花费大量时间,并且将数据读入内存然后对其进行处理可以节省大量时间和内存。
    猜你喜欢
    • 2020-01-31
    • 2021-11-19
    • 2017-03-08
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2020-04-04
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多