ruby对文件的各种操作

 
# 详情请查看../ruby/lib/ruby/1.8目录下的fileutils.rb文件
一 目录的部分操作
   1. 新建文件夹
     Dir.mkdir("f:/testdir")
   2. 删除文件夹
     Dir.rmdir("f:/testdir")
   3. 查询当前目录下的文件
     puts Dir.entries(File.join("f:","Ruby"))
 
二 文件的部分操作
 在开始之前,先介绍一下ruby对文件处理的各种模式:
 "r" :Read-only. Starts at beginning of file (default mode).
  翻译:"r" 只读。从文件起始处开始读取(默认模式)
 "r+" :Read-write. Starts at beginning of file.
 翻译:"r+"可读可写,从文件的起始处开始读取
 "w" :Write-only. Truncates existing file to zero length or creates a new file for writing.
 翻译:"w"只写,截断现有文件的长度至零,或建立一个新文件,以备写入 
 "w+" :Read-write. Truncates existing file to zero length or creates a new file for reading and writing.
 翻译:"w+"可读可写,截断现有文件的长度至零,或建立一个新文件,以备读写
 "a" :Write-only. Starts at end of file if file exists; otherwise, creates a new file for writing.
 翻译:"a"只写,若文件存在,在由文件结尾处开始写入,或则建立新文件以备写入
 "a+" :Read-write. Starts at end of file if file exists; otherwise, creates a new file for reading and writing.
 翻译:"a+"可读可写,若文件存在,在由文件结尾处开始写入,或则建立新文件以备写入
 "b" :(DOS/Windows only.) Binary file mode. May appear with any of the key letters listed above。
  翻译:"b" (Dos/Windows限定功能)二进制文件模式,可与上述各关键字一并出现
 
 1. 新建文件
 f=File.new(File.join("f:/ruby","Test.xml"), "w+")     # 文件名和格式任意
 2. 往文件中输入内容
 f.puts("<?xml version='1.0' encoding='utf-8'?>")
 f.puts('<Person>') 
 f.puts("<Name>#{NAME}</Name>")
 f.puts("<Age>55</Age>")
 f.puts("<Weight>120KG</Weight>") 
 f.puts('</Person>')   
  # 因为在捣鼓xml配置文件,就临时复制过来了,内容随意
 3. 删除文件
   path_file = File.join("f:/ruby","Test.xml")
  object_file=File.new(path_file, "w+")
  object_file.close    缺少这一步,会报“in `delete': Permission denied - f:/ruby/Test.txt (Errno::EACCES)”
  File.delete(path_file)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值