读文件

#Ruby 读取文件
#方法一
file = File.open("/Users/Desktop/demo.txt","r") 
while line = file.gets
  puts line
end

#方法二
File.open("/Users/Desktop/demo.txt","r").each_line do |line|
  puts line
end

 

写文件

File.open("/Users/Desktop/demo.txt","a+") do |f|
  f.puts "hi"
end

 

r是只读,文件已存在,指针在文件头;r+是读写方式,读写指针都在文件头。w是只写方式,w+是读写方式建立新文件,读指针在文件头。a是追加方式打开文件,指针指向文件尾;a+是读写方式打开文件,读从文件开始,写从文件尾开始。

posted on 2019-07-25 11:53  bainianminguo  阅读(2991)  评论(0编辑  收藏  举报