im trying to process a directory that contains many text files. I want
to read each file, store the text inside file and then move to the next
file. I used the following code but at the end i get an error about
Permission Denied. Can someone tell me what im doing wrong.
#get list of files
basedir = “C:/rubyfolder”
Dir.chdir(basedir)
Dir.open(basedir) do |dir|
dir.each do |file|
x = file
myfile = File.open(x, “r”)
x.close
dataclass = Manipulate.new(myfile)
end
end
x = file
myfile = File.open(x, “r”)
x.close
dataclass = Manipulate.new(myfile)
end
end
Hello Barry,
Your error probably has nothing to do with ruby. Check whether you
(the user this ruby process is running as) has read access to
C:/rubyfolder and the files within. The first couple lines of the
error stacktrace should help you track down what you don’t have
permissions on.
In the meantime, some other observations:
1: --------
Dir.open(basedir) do |dir|
dir.each do |file|
…
is equivalent to:
Dir.foreach(basedir) do |file|
…
2: --------
dir.each do |file|
x = file
This is redundant. All you’re doing is creating another reference
(‘x’) to the same object referenced by ‘file’. If you prefer the name
‘x’, you might as well write ‘dir.each do |x|’. But more likely
you’ll just want to use the ‘file’ block variable directly (or perhaps
rename it to ‘filename’).
3: --------
x.close
This won’t work. Dir#each passes each filename into the block as a
String. So ‘x’ won’t have a #close method. On a related note, a nice
way to ensure a file is closed after you’re done with it is to use the
block form of File#open:
dataclass = File.open(filename) do |file|
Manipulate.new(file)
end
im trying to process a directory that contains many text files. I want
to read each file, store the text inside file and then move to the next
file. I used the following code but at the end i get an error about
Permission Denied. Can someone tell me what im doing wrong.
Where do you get that error? Can you provide the stacktrace and
indicate where that is in the script?
#get list of files
basedir = “C:/rubyfolder”
Dir.chdir(basedir)
Dir.open(basedir) do |dir|
This won’t work as soon as basedir is a relative path!
dir.each do |file|
x = file
myfile = File.open(x, “r”)
x.close
dataclass = Manipulate.new(myfile)
end
end
thanks in advance
See also lasitha’s excellent remarks.
Cheers
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.