ruby 对文件的操作

文件路径
require 'pathname'
path1=Pathname.new(File.dirname(__FILE__)).realpath.parent  #获取文件所在父目录的绝对路径
path2=Pathname.new(File.dirname(__FILE__)).realpath  #获取文件所在目录的绝对路径
$:.unshift File.join(File.dirname(__FILE__),'..') #加载文件所在目录的父目录的相对路径至ruby全局变量
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__),'..'))) #加载文件所在目录的父目录的绝对路径至ruby全局变量
读取一个文件,将其打印出来:
lines = File .open( 'dom.js' ).readlines
puts "======================="
lines. each { |line| puts(line)}

或者:

File .open( "dom.js" ) do |file|
   while line = file.gets
     puts line
   end
end

后一种能确保文件用完后被关闭。

向目标文件追加内容:
file = File .open( "dom.js" , "a" )
file.puts "//this is new content. "
file.close

但这有时可能出现不能添加中文内容的情况,报“invalid multibyte char (US-ASCII) ”错误,我们就要在当前脚本的最上面添加这么一下注释,就没事了,即

# coding: utf-8
file = File .open( "dom.js" , "a" )
file.puts "//这是新追加的内容. "
file.close

创建一个新文件,并往其里面添加内容

# coding: utf-8
file = File . new ( "new_file.js" , "w" );
file << 'var a = "test";'
file.close;
文件重命名:
# coding: utf-8
File .rename( "new_file.js" , "new.js" ) #原来的文件名,新的文件名
删除文件
# coding: utf-8
File .delete( "new.js" ) #原来的文件名
目录操作:
# coding: utf-8
Dir .mkdir( "new" ) #创建一个新文件夹
Dir .rmdir( "new" ) #删除指定的文件夹
将一个文件拷贝到目标目标:
require 'fileutils'
FileUtils.cp 'new.js' , 'new'
将一个文件移动到目标目标:
require 'fileutils'
FileUtils.mv 'new.js' , 'new'

判断一个文件是否存在

require  'fileutils'
puts FileTest::exist?(file_path)
#false 不存在  true 存在


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值