ruby对文件的各种操作

2010-05-03  刘俊 

明天去公司接着深入研究,今天尝试过的一些操作先写下来
# 详情请查看../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)
  感谢capricorn姑娘的大力赞助 http://www.51testing.com/?150648
 
 
  
  
1383°/13778 人阅读/6 条评论 发表评论

朱斌  2010-05-04

学习


邓迎秋  2010-05-04

你也在用WATIR?


刘俊  2010-05-04

邓迎秋: 你也在用WATIR?
用了半年了,嘿嘿


周桃林  2010-08-12

我也准备需要用WATIR,可以教教么?给点资料什么的?
我的QQ34342311


刘俊  2010-08-13

周桃林: 我也准备需要用WATIR,可以教教么?给点资料什么的?
我的QQ34342311
106196615
你加这个群吧,里面很多高手


周桃林  2010-08-13

刘俊: 106196615
你加这个群吧,里面很多高手
谢谢啦~


登录 后发表评论