【问题标题】:How to find and read into files inside multiple .zip folders with Perl?如何使用 Perl 查找并读入多个 .zip 文件夹中的文件?
【发布时间】:2015-01-26 05:36:11
【问题描述】:

我有一个这样的目录结构:

Sample1
  Subdir1
    file.txt
    file.jpg
    file.fastq
    directory1.zip
          file.txt
          file.csv
          result.html
          summary.txt
    directory2.zip
          file.txt
          file.csv
          result.html
          summary.txt

一旦我处于 Subdir1 级别,我怎样才能找到解压缩这两个 .zip 文件,并将这两个 summary.txt 文件保存到两个不同的文件句柄?

这是为了进一步读取这两个文件并将它们解析成一个数组。

我被要求发布到目前为止的内容。这是非常混乱的,但这里是:

my %cellHash = ();
while (my $cellDirectory = readdir(SEQ_RUN)) {
         %cellHash { $cellDirectory } = ()
         #Descend into "trimmed" subdirectory of cell.
    my $trimmedDirectory =  $cellDirectory . "/trimmed"
        opendir (TRIMMED_CELL_DIR, $trimmedDirectory) or die $!;
        # Read the 2 ZIP files
        while (my $fastQCzip = readdir(TRIMMED_CELL_DIR)) {
         #only if .zip  
        # File 1 always ends in _1_fastqc.zip
        # File 2 always ends in _2_fastqc.zip

my $summaryFastQC = Archive::Zip->new();
unless ( $summaryFastQC->read( $fastQCzip ) == AZ_OK ) {
    die 'read error'
    }
# Parse output: cellHash {cellName} [ R1 TESTS ] [ R2 TESTS ]
open QUALITY_SUMMARY, "filename.txt" or die $!;

【问题讨论】:

  • 发布您目前所拥有的。

标签: perl unzip file-handling compression


【解决方案1】:

使用模块 File::Find 可以更轻松地查找 zip 文件。

用于搜索文件的代码块甚至可以通过将它传递给 find2perl 从通常的 find 命令创建。

例如: find2perl 查找。 -name "*.zip"

产生:

sub wanted {
    /^.*\.zip\z/s
    && print("$name\n");
}

所以你可以这样做:

#!/usr/bin/perl
#

use strict;
use warnings;

use File::Find;


sub wanted {
    /^.*\.zip\z/s
    && print("$File::Find::dir/$_\n");
}

my @dirs = ("somedir", "anotherdir");

my @zips = find(\&wanted, @dirs);

print "@zips\n";

http://perldoc.perl.org/File/Find.html

然后,要保存 summary.txt 的实例,您将扫描档案以查找该名称并将文件保存到某个目录。为避免覆盖,您可以通过一些任意扩展名将它们分开:

my $wanted = "summary.txt";
my $suffix = 0;
foreach my $zipname (@zips)
{
    my $zip = Archive::Zip->new($zipname);
    foreach my $member ($zip->members)
    {
        next unless ($member->fileName =~ /\/$wanted$/);

        $suffix++;
        if ($member->extractToFileNamed("$wanted.$suffix") != 'AZ_OK') {
            die("Could not create $newname");
        }
    }
}

http://www.perlmonks.org/?node_id=104653

【讨论】:

    猜你喜欢
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多