gpt4 book ai didi

ruby - 读取 zip 存档中的文件,无需解压缩存档

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:46 24 4
gpt4 key购买 nike

我有一个包含 100 多个 zip 文件的目录,我需要读取 zip 文件中的文件以进行一些数据处理,而无需解压缩存档。

是否有一个 Ruby 库可以在不解压缩文件的情况下读取 zip 存档中的文件内容?

使用rubyzip 报错:

require 'zip'

Zip::File.open('my_zip.zip') do |zip_file|
# Handle entries one by one
zip_file.each do |entry|
# Extract to file/directory/symlink
puts "Extracting #{entry.name}"
entry.extract('here')

# Read into memory
content = entry.get_input_stream.read
end
end

给出这个错误:

test.rb:12:in `block (2 levels) in <main>': undefined method `read' for Zip::NullInputStream:Module (NoMethodError)
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/entry_set.rb:42:in `call'
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/entry_set.rb:42:in `block in each'
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/entry_set.rb:41:in `each'
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/entry_set.rb:41:in `each'
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/central_directory.rb:182:in `each'
from test.rb:6:in `block in <main>'
from .gem/ruby/gems/rubyzip-1.1.6/lib/zip/file.rb:99:in `open'
from test.rb:4:in `<main>'

最佳答案

如果条目是目录而不是文件,则返回 Zip::NullInputStream,会是这种情况吗?

下面是代码的更健壮的变体:

#!/usr/bin/env ruby

require 'rubygems'
require 'zip'


Zip::File.open('my_zip.zip') do |zip_file|
# Handle entries one by one
zip_file.each do |entry|
if entry.directory?
puts "#{entry.name} is a folder!"
elsif entry.symlink?
puts "#{entry.name} is a symlink!"
elsif entry.file?
puts "#{entry.name} is a regular file!"

# Read into memory
entry.get_input_stream { |io| content = io.read }

# Output
puts content
else
puts "#{entry.name} is something unknown, oops!"
end
end
end

关于ruby - 读取 zip 存档中的文件,无需解压缩存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com