读取和写入文件
我是 Perl 新手,正在尝试在 Perl 中读取和写入 csv 文件。但没有任何事情发生,有人可以帮助我解决问题所在。我可以使用“<”毫无问题地阅读但我无法写作。
use strict;
use warnings;
use Text::CSV_XS;
my $file = 'file.csv';
my $csv = Text::CSV_XS->new();
open (InCSV, '+>>', $file) or die $!;
while (<InCSV>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
if($columns[1] eq "01") {
my $str = "Selected $columns[6] \n ";
push(@columns,$str);
print InCSV join("," , @columns), "\n";
}
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close InCSV;
I am new to perl and am trying to read and write to a csv file in perl. But nothing happens can some one help me where the problem is. I am able to read without a problem using '<' but I am unable to write.
use strict;
use warnings;
use Text::CSV_XS;
my $file = 'file.csv';
my $csv = Text::CSV_XS->new();
open (InCSV, '+>>', $file) or die $!;
while (<InCSV>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
if($columns[1] eq "01") {
my $str = "Selected $columns[6] \n ";
push(@columns,$str);
print InCSV join("," , @columns), "\n";
}
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close InCSV;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以
+>>
模式打开文件将查找文件末尾,因此除非您seek
回到开头(或文件的中间)。要以读/写模式打开且文件光标位于文件开头,请使用+<
模式。也就是说,您可能需要重新考虑解决此问题的方法。看起来您正在尝试读取一行数据,修改它,然后将其写回到文件中。但按照您的做法,您将覆盖下行数据,而不是刚刚读取的行,而且无论如何,新数据比旧数据更长(具有更多字节)。这肯定会损坏您的数据文件。
一些更好的方法可能是
首先读取并处理所有数据,然后关闭并使用处理后的数据覆盖输入
写入数据在处理它时将其保存到临时文件,然后用临时文件覆盖输入(另请参阅有关 perl 解释器的 就地编辑模式)
使用像
Tie::File
这样的模块来处理此任务的基于行的 I/OOpening a file in
+>>
mode will seek to the end of the file, so there will be nothing to read unless youseek
back to the beginning (or the middle) of the file. To open in read/write mode with the file cursor at the beginning of the file, use+<
mode.That said, you probably want to rethink your approach to this problem. It looks like you are trying to read a row of data, modify it, and write it back to the file. But the way you have done it, you are overwriting the next row of data rather than the row you have just read, and anyway the new data is longer (has more bytes) than the old data. This is certain to corrupt your data file.
Some better approaches might be to
read and process all data first, then close and overwrite the input with processed data
write data to a temporary file while you are processing it, then overwrite the input with the temporary file (see also about the perl interpreter's in-place editing mode)
use a module like
Tie::File
to handle the line-based I/O for this task