Categories

Scripting with Ruby : be careful with File.open

Once again, I spend a long time debugging something which was quite obvious (well, at least when I discovered the solution…)
Trying to copy all the files from a .m3u playlist file (in each line there is a file path), I used ruby (well bash and zsh are not as funny as ruby), and especially the FileUtils.cp function.
The code is as follow :

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'fileutils'
count=0
string = String.new
File.open("/home/anthony/Documents/playlist_ok.m3u").each { |line|
if(count!=0)
if((!line.include?"#"))
string = line.chomp
FileUtils.cp string,'./'
end
end
count =  count+1
}
puts "Nombre lignes traitées : " + count.to_s

Well, my mistake was to forget to add the line :
string = line.chomp
because when you don’t, Ruby add the extra « \n » at the end of every line, and then FileUtils returns to you this very explicit message :

/usr/lib/ruby/1.8/fileutils.rb:1200:in `stat': No such file or directory - (Errno::ENOENT)
from /usr/lib/ruby/1.8/fileutils.rb:1200:in `lstat'
from /usr/lib/ruby/1.8/fileutils.rb:1178:in `stat'
from /usr/lib/ruby/1.8/fileutils.rb:1260:in `copy_file'
from /usr/lib/ruby/1.8/fileutils.rb:463:in `copy_file'
from /usr/lib/ruby/1.8/fileutils.rb:383:in `cp'
from /usr/lib/ruby/1.8/fileutils.rb:1395:in `fu_each_src_dest'
from /usr/lib/ruby/1.8/fileutils.rb:1409:in `fu_each_src_dest0'
from /usr/lib/ruby/1.8/fileutils.rb:1393:in `fu_each_src_dest'
from /usr/lib/ruby/1.8/fileutils.rb:382:in `cp'
from /serveur/anthony/ruby/export_playlist_to_files.rb:12
from /serveur/anthony/ruby/export_playlist_to_files.rb:5:in `each'
from /serveur/anthony/ruby/export_playlist_to_files.rb:5

And believe me, it takes a while to debug… (irb was helful to solve this bug by the way !)

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">