Ruby Rename File Permission Error

  question, ruby

Today, we plan to rename all files in a directory in batch.
The code is as follows:

Dir.foreach ("life") do |filename|
 if newfile=filename.sub(/\[.*\]\./,"")
 #File.chmod(0755, filename) rescue nil
 File.rename(filename,newfile)
 #puts File.writable?  (filename)
 end
 end

Results: Permission denied, screenshots are as follows

图片描述

Have you ever encountered this kind of situation, please ask the great god to solve it! !

Well, it has been solved. I forgot to remove “..” and “..”, and found that if the pathname is Chinese, there will be coding problems. In order to save trouble, I directly changed the pathname into English, and then it is ok. The new code is as follows:

Dir.foreach ("BBC.Life") do |filename|
 if newfile=filename.sub(/\[.*\]\./,"")
 #File.chmod(0755, filename) rescue nil
 next if filename=="."
 next if filename==".."
 File.rename("BBC.Life/"+filename,"BBC.Life/"+newfile)
 #print filename,"   =>  ",newfile,"\n"
 end
 end