Ruby常用文件操作代码实例

所属分类: 脚本专栏 / ruby专题 阅读数: 1035
收藏 0 赞 0 分享
#建立一个222.rb文件并且输入字符
file = File.open("222.rb","w+")
file.puts "123\nwadwa\n12124124\ndwdw"
file.close


#输出222.rb的内容
File.open("222.rb","r+") do |file|
while line = file.gets
puts line
end
end


#直接用IO操作文件
IO.foreach("222.rb") do |line|
puts line if line =~/abc/ #输出匹配到了'abc'的所在行
puts line if line !~/qwe/ #输出没有匹配到'qwe'的所在行
end



#输出文件的绝对路径
puts File.expand_path("222.rb")


#count chars from a file
file= File.new("222.rb")
w_count = 0
file.each_byte do |byte|
w_count += 1 if byte ==?1
end
puts "#{w_count}"


#create new file and write some words there
print "The file now is exist? --> " 
puts File.exist?("asd.txt")#判断文件是否存在

file= File.new("asd.txt","w")
print "The file now is exist? --> " 
puts File.exist?("asd.txt")

file.write("hehe\nhahah")


#io.stream operation
require 'stringio'
ios = StringIO.new("abcdef\n ABC \n 12345")
ios.seek(5) #把偏移指针移到5(e字母所在位置)
ios.puts("xyz3") #从5开始覆写原有数据
puts ios.tell #tell--Returns the current offset (in bytes) of ios. 
puts ios.string
puts ios.string.dump #忽略\n的转义


#another example
require 'stringio'
ios = StringIO.new("abcdef\nq9ert \n 12345")
ios.seek(3)
ios.ungetc(?w) #replace the char at index 3
puts "Ptr = #{ios.tell}"
s1 = ios.gets #filte the "\n" 
s2 = ios.gets
puts s1
puts s2


#Ruby打开文件并写入数据操作
txt = File.open("文件路径","w+")
txt.puts '要写入的文件内容'
txt.close
#从文件里读取数据
num = File.readlines("文件路径")[0].chomp
#打开文件的方法
system("notepad 文件路径")

更多精彩内容其他人还在看

Rails link_to 详解

想学习rauks link_to的朋友可以参考下面的例子。
收藏 0 赞 0 分享

ruby 小脚本搞定CVS服务器更换后checkout下来的工程迁移

CVS换了新的服务器,原来的工程需要更改Server配置,这个东东手工做起来 可是个体力活,写了一个脚本分发下来。
收藏 0 赞 0 分享

Ruby 魔法 学习笔记之一

Ruby的许多动态特性,让Ruby具有很多魔法,这个魔法足以让你来定制你自己的语言DSL, Rails就是Ruby在Web的DSL.
收藏 0 赞 0 分享

Ruby self在不同环境的含义

Ruby的self在不同的环境中有不同的含义,这点和java的this不同,原因是java实际上只有一种环境--在class的实例方法定义中使用,代表访问这个方法参数自动传进的那个对象。
收藏 0 赞 0 分享

ruby 程序的执行顺序

ruby程序的执行是顺序执行的,他是从脚本的第一行执行到最后一行,但是实际执行顺序是
收藏 0 赞 0 分享

ruby on rails 代码技巧

对于rails的一些使用技巧的代码
收藏 0 赞 0 分享

ruby 标准类型总结

诠释分析了ruby的标准类型,学习ruby的朋友,需要了解和掌握的。
收藏 0 赞 0 分享

ruby 去掉文件里重复的行

以前合并后台字典时,有重复的都是用vbs去,最近又看了一天的ruby,想起来写一下,没想到代码如此精简
收藏 0 赞 0 分享

Ruby rails 页面跳转(render和redirect_to)

今天在做R.R.log的时候发现个问题,在修改密码的时候如果没有通过校验,没有显示校验错误的信息。
收藏 0 赞 0 分享

Ruby 取得指定月日期数的方法

取得指定月日期数的Ruby代码
收藏 0 赞 0 分享
查看更多