2013-02-13 84 views
1

我想从包含大约200个文本文件的目录中读取文件行,但是,我无法让Ruby逐行读取它们。我之前做过,使用一个文本文件,而不是从目录中读取它们。如何从目录逐行打开和读取文件?

我可以获取文件名作为字符串,但我努力打开它们并阅读每一行。

以下是我尝试过的一些方法。

方法1:

def readdirectory 
    @filearray = [] 
Dir.foreach('mydirectory') do |i| 
# puts i.class 
    @filearray.push(i) 
    @filearray.each do |s| 
    # @words =IO.readlines('s') 
     puts s 
    end#do 
# puts @words 
end#do 

end#readdirectory 

方法2:

def tryread 
Dir.foreach('mydir'){ 
    |x| IO.readlines(x) 
} 

end#tryread 

方法3:

def tryread 
Dir.foreach('mydir') do |s| 
    File.readlines(s).each do |line| 
       sentence =line.split 
    end#inner do 

end #do 
end#tryread 

随着每一次试图打开循环函数传递的字符串,我不断收到错误:

Permission denied - . (Errno::EACCES) 
+3

因此,您无权读取文件。 – 2013-02-13 14:45:03

+0

@SergioTulentsev说的+1。错误代码说明了主要/第一个问题。 'readlines'不是'File.foreach',因为它在#2和#3中更具可扩展性。 – 2013-02-13 15:05:00

回答

0

sudo ruby reader.rb或任何你的文件名是。

因为权限是基于过程的,所以如果过程读数没有它们,就不能读取具有提升权限的文件。

唯一的解决方案是运行具有更多权限的脚本,或者调用另一个已运行更高权限的进程来为您读取。

0

感谢所有的答复,我做了一些试验和错误的,并得到了work.This是我用

Dir.entries('lemmatised').each do |s| 
     if !File.directory?(s) 

     file = File.open("pathname/#{s}", 'r') 

     file.each_line do |line| 
      count+=1 
      @words<<line.split(/[^a-zA-Z]/) 
     end # inner do 
      puts @words 
     end #if 
    end #do 
0

试试这个语法,

#it'll hold the lines 
f = [] 

#here test directory contains all the files, 
#write the path as per the your computer, 
#mine's as you can see, below 

#fetch filenames and keep in sorted order 
a = Dir.entries("c:/Users/lordsangram/desktop/test") 

#read the files, line by line 
Dir.chdir("c:/Users/lordsangram/desktop/test") 

#beginning for i = 1, to ignore first two elements of array a, 
#which has no associated file names 
2.upto(a.length-1) do |i| 
    File.readlines("#{a[i]}").each do |line| 
     f.push(line) 
    end 
end 

f.each do |l| 
    puts l 
end 
0

@the锡人 - >你需要避免处理“。”和“..”,它们在Dir.foreach中列出并给予权限拒绝错误。一个简单的if应该修复你的所有apporoaches。

Dir.foreach(ARGV[0]) do |f| 
    if f != "." and f != ".." 
    # code to process file 
    # example 
    # File.open(ARGV[0] + "\\" + f) do |file| 
    # end 
    end 
end