我正在尝试重命名zip文件和目录。我尝试了三种不同的方式,都没有用。这样做的正确命令是什么?
以下是我的代码的摘录:
require 'zip/zip'
...
def renaming_zip(zip_file)
Zip::ZipFile.open(zip_file).each do |entry|
if entry.name == "mimetype"
puts "#{entry.name} is a file ? #{File.file? entry.name}"
puts " class ? #{entry.class}"
new_filename = "#{entry.name.gsub("mimetype", "#mimetype-new")}"
#found_entry = entry.get_entry("mimetype")
#found_entry.name = new_filename #1st try
puts " new filename #{new_filename}"
#File.rename(entry.name, new_filename) #2nd try
#entry.rename(entry.name, new_filename) #3rd try
end
end
end
如果我在没有任何重命名试用命令的情况下执行,我会得到此输出,因此您可以看到该文件存在于zip中。它不是File类,而是Zip :: ZipEntry类,我可以解析新名称。
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
第一次尝试(取消注释),我收到此错误:
mimetype is a file ? false
class ? Zip::ZipEntry
Uncaught exception: undefined method `get_entry' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:45:in `block in renaming_zip'
...
第二次尝试(取消注释),我收到此错误:
Uncaught exception: No such file or directory - (mimetype, #mimetype-new)
/Users/.../app/lib/zip_rename.rb:48:in `rename'
/Users/.../app/lib/zxp_rename.rb:48:in `block in renaming_zip'
...
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
第三次尝试(取消注释),我收到此错误:
mimetype is a file ? false
class ? Zip::ZipEntry
new filename #mimetype-new
Uncaught exception: undefined method `rename' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:49:in `block in renaming_zip'
...
答案 0 :(得分:0)
要在条目上重命名条目呼叫重命名。
第一次尝试失败,因为您在get_entry
上呼叫entry
,它应该在ZipFile
上。
第二次尝试失败,因为代码以双引号结束字符串。
new_filename = entry.name.gsub('mimetype', '#mimetype-new')
第三次尝试失败,因为该对象为mimetype:Zip::ZipEntry
且不是Zip::ZipEntry
正确的方法是
new_filename = "#mimetype-new"
Zip::ZipFile.open(zip_file).each do |zipfile|
files = zipfile.select(&:file?)
files.each do |file|
if entry.name == "mimetype"
entry.rename(entry.name, new_filename)
end
end
end
答案 1 :(得分:0)
使用rubyzip重命名zip内的文件:
require 'zip'
old_name = 'mimetype'
new_filename = '#mimetype-new'
Zip::ZipFile.open(zip_file_path).each do |zipfile|
files = zipfile.select(&:file?)
file = files.find{|f| f.name == old_name}
zipfile.rename(file.name, new_filename) if file
end