ruby 遍历文件

简介:

ruby遍历文件内容,基本思路是逐行读取逐行打印,也是比较普遍的方法:

1
2
3
4
5
6
7
8
#!/usr/bin/env ruby
#Encoding:utf8
 
file =  File .open( "/tmp/abc.txt" )
file.each_line  do  |line|
   print line
end
file.close

直接写成块,好处是无需显性的关闭文件句柄。

1
2
3
4
5
File .open( '/tmp/abc.txt' do  |file|
   file.each_line  do  |line|
     print line
   end
end


另外一种写法,一次性读取一次性打印,相对耗费更多内存,小文件场合比上面的方法更快。不推荐操作大文件。

1
2
3
4
5
#!/usr/bin/env ruby
# Encoding:utf8
 
wholefile =  File .read( "/tmp/abc.txt" )
print wholefile


小结

1、第一种方法比较像sed,awk之类的流编辑器,第二种方法跟cat一样暴力。

2、File.read不需要显式关闭文件句柄。


扩展

在打开文件前,判断文件是否存在

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env ruby
# Encoding: utf8
if  File .exist?( "/tmp/abc.txt" )
   file =  File .open( "/tmp/abc.txt" )
   file.each_line  do  |line|
     print line
   end
   file.close
else
   puts  "error:file not exist"
end

逐行读取,将文件名作为ruby脚本的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env ruby
# Encoding: utf8
 
filename =  ARGV [ 0 ]
if  File .exist?(filename)
   file =  File .open(filename)
   file.each_line  do  |line|
     print line
   end
   file.close
else
   puts  "error:file not exist"
end










本文转自 紫色葡萄 51CTO博客,原文链接:http://blog.51cto.com/purplegrape/1884333,如需转载请自行联系原作者
目录
相关文章
|
5月前
|
存储 Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby
|
5月前
|
Ruby