Ruby常用文件操作方法
一、新建文件
f=File.new(File.join("C:","Test.txt"),"w+") f.puts("IamJack") f.puts("HelloWorld")
文件模式
"r":Read-only.Startsatbeginningoffile(defaultmode).
"r+":Read-write.Startsatbeginningoffile.
"w":Write-only.Truncatesexistingfiletozerolengthorcreatesanewfileforwriting.
"w+":Read-write.Truncatesexistingfiletozerolengthorcreatesanewfileforreadingandwriting.
"a":Write-only.Startsatendoffileiffileexists;otherwise,createsanewfileforwriting.
"a+":Read-write.Startsatendoffileiffileexists;otherwise,createsanewfileforreadingandwriting.
"b":(DOS/Windowsonly.)Binaryfilemode.Mayappearwithanyofthekeyletterslistedabove
二、读取文件
file=File.open(File.join("C:","Test.txt"),"r") file.each{|line|print"#{file.lineno}.",line} file.close
三、新建、删除、重命名文件
File.new("books.txt","w") File.rename("books.txt","chaps.txt") File.delete("chaps.txt")
四、目录操作
1 创建目录
Dir.mkdir("c:/testdir") #删除目录 Dir.rmdir("c:/testdir") #查询目录里的文件 pDir.entries(File.join("C:","Ruby")).join('') #遍历目录 Dir.entries(File.join("C:","Ruby")).each{ |e|putse }
1、ARGVandARGF
ARGV ARGV<<"cnblogslink.txt" #ThegetsmethodisaKernelmethodthatgetslinesfromARGV printwhilegets pARGV.class
ARGF whileline=ARGF.gets printline end