标题: ruby文件操作 [打印本页] 作者: 2gua 时间: 2011-06-26 07:16 标题: ruby文件操作 1、文件的打开与关闭
``r'' Read-only, starts at beginning of file (default mode).
``r+'' Read-write, starts at beginning of file.
``w'' Write-only, truncates existing file to zero length or creates a new file for writing.
``w+'' Read-write, truncates existing file to zero length or creates a new file for reading and writing.
``a'' Write-only, starts at end of file if file exists, otherwise creates a new file for writing.
``a+'' Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.
``b'' (DOS/Windows only) Binary file mode (may appear with any of the key letters listed above).
使用file.new方法获取一个文件句柄来对文件操作,操作结束后file.close来关闭文件。
file.open方法是new方法的扩充,该方法可有代码块,该代码块结束后自动close,而且在操作过程中发生错误时能够自动收集错误并推出
如
file.open("filepath") do |file|
file.each do |line| ... end
end
一些文件的常用命令:
File.open(dir+"/read.txt","w") do |file|
file.puts("djkjsadlkjdkdsfdsee")
end
3、查询目录及子目录文件
require "find"
Find.find("/etc/passwd", "/var/spool/lp1", ".") do |f|
Find.prune if f == "."
puts f
end
原型:ref.find( [ aName ]* ) {| aFileName | block }
prune:Skips the current file or directory, restarting the loop with the next entry. If the current file is a directory, that directory will not be recursively entered. Meaningful only within the block associated with Find::find.