【发布时间】:2015-03-10 00:40:23
【问题描述】:
我在主文件夹中有几个子文件夹。每个子文件夹中都有一个 .txt 文件。首先,代码将在主文件夹中创建“结果”文件夹。它将在 .txt 中搜索“atom”字,并将包含“Frequencies --”字的列作为列打印到输出文件(在结果文件夹中)。它将为子文件夹中的每个 .txt 文件执行此过程。输出文件名可以与子文件夹相同。该代码创建了“结果”文件夹,但它给出了以下错误。我该如何解决?
Error:Failed to open "./freq.txt" for writing: No such file or directory at ./analysis.pl line 27
#!/usr/bin/env perl
use strict;
use warnings;
use File::Path qw/make_path/;
use Cwd;
my $dir = cwd();
opendir (my $dh, $dir) or die "Unable to open current directory! $!\n";
my @subdirs = grep { /^\.\.?\z/ } readdir($dh) or die "Unable to read directory! $!\n";
closedir $dh;
my $result_path = "$dir/results";
make_path("$result_path");
for my $subdir ( sort @subdirs ) {
chdir($dir);
next unless -d $subdir;
make_path("$result_path/$subdir");
my $search_text1 = qr/Frequencies --/;
my $infile1="$subdir/freq.txt";
my $outfile1="$result_path/output.txt";
# Line 27 below
open my $in_fh1, '<', $infile1 or die qq{Failed to open "$infile1" for writing: $!};
open my $out_fh1,'>', $outfile1 or die qq{Failed to open "$outfile1" for writing: $!};
while (<$in_fh1>) {
next unless /$search_text1/;
my @fields1 = split;
print $out_fh1 join("\t", $fields1[1,2,3]), "\n";
}
close($in_fh1);
close($out_fh1);
chdir("..");
}
输入文件:
Frequencies -- 23.5214 40.9023 56.7856
Red. masses -- 6.7793 1.0546 5.5674
Frc consts -- 0.0022 0.0010 0.0106
IR Inten -- 2.4504 0.2236 0.6152
Atom AN X Y Z X Y Z X Y Z
1 6 0.00 0.01 0.06 0.00 0.00 0.01 0.00 -0.01 0.11
2 6 0.00 0.00 0.09 0.00 0.00 0.01 0.00 0.00 0.10
3 7 0.00 0.01 0.19 0.00 0.00 0.03 0.00 0.00 0.02
Frequencies -- 91.1714 97.2522 123.2844
Red. masses -- 7.3071 9.6551 6.3036
Frc consts -- 0.0358 0.0538 0.0564
IR Inten -- 0.5639 11.9103 2.8105
Atom AN X Y Z X Y Z X Y Z
1 6 0.01 -0.14 -0.01 -0.01 0.04 0.04 0.00 0.00 -0.23
2 6 0.00 -0.12 0.02 0.00 0.04 0.02 0.01 0.01 0.17
3 7 0.00 -0.14 -0.05 0.00 0.04 -0.22 0.01 0.00 -0.15
【问题讨论】:
-
您正试图打开伪目录
.和..中的文件,而不是真正的子目录。你似乎在反复问非常相似的问题,然后忽略了你得到的答案。您为什么不使用您对上一个问题接受的解决方案? -
当您发布脚本时,请至少正确缩进,以便其他人阅读。
标签: perl