gpt4 book ai didi

Ruby:检查 .zip 文件是否存在,然后解压

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:43 25 4
gpt4 key购买 nike

2 个小问题来创建我正在寻找的效果。如何检查扩展名为 .zip 的目录中是否存在文件?如果它确实存在,我需要创建一个与 .zip 同名的文件夹,但该文件夹没有 .zip 扩展名。然后我需要将文件解压到文件夹中。

其次,如果文件夹中有多个.zip文件怎么办?

我正在做这样的事情并试图将它放入 ruby 中

`mkdir fileNameisRandom`
`unzip fileNameisRandom.zip -d fileNameisRandom`

在类似的帖子上我发现了类似的东西

Dir.entries("#{Dir.pwd}").select {|f| File.file? f}

我知道它会检查目录中的所有文件并确保它们是一个文件。问题是我不知道如何确保它只是 .zip 的扩展

此外,我还发现了 Glob 函数,它检查文件名的扩展名:http://ruby-doc.org/core-1.9.3/Dir.html在这种情况下,我如何确保文件存在,如果不存在,我可以打印出错误。

来 self 现在的评论

if Dir['*.zip'].first == nil #check to see if any exist
puts "A .zip file was not found"
elsif Dir['*.zip'].select {|f| File.file? f} then #ensure each of them are a file
#use a foreach loop to go through each one
Dir['*.zip'].select.each do |file|
puts "#{file}"
end ## end for each loop
end

最佳答案

这里有一种方法可以减少分支:

# prepare the data
zips= Dir['*.zip'].select{ |f| File.file? }

# check if data is sane
if zips.empty?
puts "No zips"
exit 0 # or return
end

# process data
zips.each do |z|

end

对于其他程序员来说,这种模式更容易遵循。

您也可以使用名为 rubyzip

的 ruby​​ gem 来完成此操作

gem 文件:

source 'https://rubygems.org'
gem 'rubyzip'

运行包

解压.rb:

require 'zip'

zips= Dir['*.zip'].select{ |f| File.file? }

if zips.empty?
puts "No zips"
exit 0 # or return
end

zips.each do |zip|
Zip::File.open(zip) do |files|
files.each do |file|
# write file somewhere
# see here https://github.com/rubyzip/rubyzip
end
end
end

关于Ruby:检查 .zip 文件是否存在,然后解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21175528/

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